zoukankan      html  css  js  c++  java
  • Socket通信流程及示例

    代码就是最好的文档

    代码演示:

    // 服务端代码

    public class ServerSocket {
    public static void main(String[] args) throws IOException {
    java.net.ServerSocket ss = new java.net.ServerSocket(65000);
    while(true){
    Socket socket = ss.accept();
    new LengthCalculator(socket).start();
    }
    }
    }
    // 客户端代码
    public class ClientSocket {
    public static void main(String[] args) throws IOException {
    Socket socket = new Socket("127.0.0.1", 65000);
    InputStream inputStream = socket.getInputStream();
    OutputStream outputStream = socket.getOutputStream();
    outputStream.write(new String("小日本,去你的").getBytes());
    int ch = 0;
    byte[] buff = new byte[1024];
    ch = inputStream.read(buff);
    String content = new String(buff,0,ch);
    System.out.println(content);
    inputStream.close();
    outputStream.close();
    socket.close();
    }
    }

    // 处理客户端请求子线程

    public class LengthCalculator extends Thread {
        private Socket socket;
    LengthCalculator(Socket socket){
    this.socket = socket;
    }

    @Override
    public void run() {
    try {
    OutputStream outputStream = socket.getOutputStream();
    InputStream inputStream = socket.getInputStream();
    int ch = 0;
    byte[] buff = new byte[1024];
    ch = inputStream.read(buff);
    String content = new String(buff,0,ch);
    System.out.println(content);

    outputStream.write(String.valueOf(content.length()).getBytes());
    inputStream.close();;
    outputStream.close();
    socket.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    super.run();
    }
    }



  • 相关阅读:
    架构基础-容量评估
    golang版本实现版本号比较-从易到解决bug
    数组模拟栈
    稀疏数组
    密码生成器
    01-gopsutil包使用
    02从零开始学习GO语言--标识符、关键字、变量和常量
    Go语言简介
    从零开始学习GO语言-搭建Go语言开发环境-快速开发入门第一个小程序
    ES6学习总结之 Module
  • 原文地址:https://www.cnblogs.com/niuyg928/p/15139608.html
Copyright © 2011-2022 走看看