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();
    }
    }



  • 相关阅读:
    【python中调用shell命令使用PIPE】使用PIPE作为stdout出现假卡死的情况——将stdout重定向为输出到临时文件
    二分查找
    MongoDB安装及启动
    Python文件IO(普通文件读写)
    Python面向对象--高级(二)
    Python面向对象--高级(一)
    Python类与对象--基础
    Python生成器、装饰器
    Python函数式编程
    Python函数及参数
  • 原文地址:https://www.cnblogs.com/niuyg928/p/15139608.html
Copyright © 2011-2022 走看看