欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

socket的多线程实现

程序员文章站 2023-11-23 00:02:28
步骤: 1、服务端创建ServerSocket,循环调用accept()等待客户端连接; 2、客户端创建socket并请求与服务端对话; 3、服务端接收客户端的请求,创建socket与客户端进行专线连接; 4、服务端监测是否接收到消息,长时间没有接收到消息则关闭连接; public class Se ......

步骤:

  1、服务端创建serversocket,循环调用accept()等待客户端连接;

  2、客户端创建socket并请求与服务端对话;

  3、服务端接收客户端的请求,创建socket与客户端进行专线连接;

  4、服务端监测是否接收到消息,长时间没有接收到消息则关闭连接;

  public class serversocketthread extends thread{

  private socket socket = null;

  public serversocketthread (socket socket){
  this.socket = socket;
  }
  @override
  public void run(){
    try {
      inputstream inputstream = socket.getinputstream();
      outputstream outputstream = socket.getoutputstream();
      bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(inputstream));
      if(bufferedreader.readline()!=null){
        string read = bufferedreader.readline();
        system.out.println(read);
        system.out.println(str2hexstr(read));
      }
    /**
    * 关闭输出流
    */
    socket.shutdownoutput();


    /**
    * 关闭相对应的资源
    */
    outputstream.close();
    bufferedreader.close();
    inputstream.close();
    socket.close();
    } catch (ioexception e) {
    e.printstacktrace();
    }


  }
}

public class socketserver {
  public static void main(string[] args) {
    try {
      serversocket serversocket = new serversocket(8888);
      socket socket = null;
      int clientcount = 0;

      while(true){
        socket = serversocket.accept();
        serversocketthread serversocketthread = new serversocketthread(socket);
        serversocketthread.start();
        clientcount++;
        system.out.println("客户端数量为:"+clientcount);
      }
    } catch (ioexception e) {
    e.printstacktrace();
  }
  }
}