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



  • 相关阅读:
    linux之参数实用讲解
    Linux脚本中调用SQL,RMAN脚本
    shell for参数
    Linux Shell参数替换
    Python OOP(1)
    Python 不可变对象
    Python set
    Python tuple
    Python list,tuple,dict and set
    Python 可变长度函数参数
  • 原文地址:https://www.cnblogs.com/niuyg928/p/15139608.html
Copyright © 2011-2022 走看看