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

基于BIO的Java Socket通信详解

程序员文章站 2024-02-20 12:33:22
bio,即阻塞io,在基于socket的消息通信过程中,socket服务端向外部提供服务,而socket客户端可以建立到socket服务端的连接,进而发送请求数据,然后等待...

bio,即阻塞io,在基于socket的消息通信过程中,socket服务端向外部提供服务,而socket客户端可以建立到socket服务端的连接,进而发送请求数据,然后等待socket服务端处理,并返回处理结果(响应)。
基于bio的通信,socket服务端会发生阻塞,即在监听过程中每次accept到一个客户端的socket连接,就要处理这个请求,而此时其他连接过来的客户端只能阻塞等待。可见,这种模式下socket服务端的处理能力是非常有限的,客户端也只能等待,直到服务端空闲时进行请求的处理。

bio通信实现

下面基于bio模式,来实现一个简单的socket服务端与socket客户端进行通信的逻辑,对这种通信方式有一个感性的认识。具体逻辑描述如下:
1、socket客户端连接到socket服务端,并发送数据“i am the client n.”;
2、socket服务端,监听服务端口,并接收客户端请求数据,如果请求数据以“i am the client”开头,则响应客户端“i am the server, and you are the nth client.”;

socket服务端实现,代码如下所示:

package org.shirdrn.java.communications.bio; 
 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.outputstream; 
import java.net.serversocket; 
import java.net.socket; 
 
/** 
 * 基于bio的socket服务器端 
 * 
 * @author shirdrn 
 */ 
public class simplebiotcpserver extends thread { 
   
  /** 服务端口号 */ 
  private int port = 8888; 
  /** 为客户端分配编号 */ 
  private static int sequence = 0; 
   
  public simplebiotcpserver(int port) { 
    this.port = port; 
  } 
   
  @override 
  public void run() { 
    socket socket = null; 
    try { 
      serversocket serversocket = new serversocket(this.port); 
      while(true) { 
        socket = serversocket.accept(); // 监听 
        this.handlemessage(socket); // 处理一个连接过来的客户端请求 
      } 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
  } 
   
  /** 
   * 处理一个客户端socket连接 
   * @param socket 客户端socket 
   * @throws ioexception 
   */ 
  private void handlemessage(socket socket) throws ioexception { 
    inputstream in = socket.getinputstream(); // 流:客户端->服务端(读) 
    outputstream out = socket.getoutputstream(); // 流:服务端->客户端(写) 
    int receivebytes; 
    byte[] receivebuffer = new byte[128]; 
    string clientmessage = ""; 
    if((receivebytes=in.read(receivebuffer))!=-1) { 
      clientmessage = new string(receivebuffer, 0, receivebytes); 
      if(clientmessage.startswith("i am the client")) { 
        string serverresponsewords =  
          "i am the server, and you are the " + (++sequence) + "th client."; 
        out.write(serverresponsewords.getbytes()); 
      } 
    } 
    out.flush(); 
    system.out.println("server: receives clientmessage->" + clientmessage); 
  } 
 
  public static void main(string[] args) { 
    simplebiotcpserver server = new simplebiotcpserver(1983); 
    server.start(); 
  } 
} 

上述实现,没有进行复杂的异常处理。

socket客户端实现,代码如下所示:

package org.shirdrn.java.communications.bio; 
 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.outputstream; 
import java.net.socket; 
import java.net.unknownhostexception; 
import java.util.date; 
 
/** 
 * 基于bio的socket客户端 
 * 
 * @author shirdrn 
 */ 
public class simplebiotcpclient { 
   
  private string ipaddress; 
  private int port; 
  private static int pos = 0; 
   
  public simplebiotcpclient() {} 
   
  public simplebiotcpclient(string ipaddress, int port) { 
    this.ipaddress = ipaddress; 
    this.port = port; 
  } 
 
  /** 
   * 连接socket服务端,并模拟发送请求数据 
   * @param data 请求数据 
   */ 
  public void send(byte[] data) { 
    socket socket = null; 
    outputstream out = null; 
    inputstream in = null; 
    try { 
      socket = new socket(this.ipaddress, this.port); // 连接 
      // 发送请求 
      out = socket.getoutputstream(); 
      out.write(data);  
      out.flush(); 
      // 接收响应 
      in = socket.getinputstream(); 
      int totalbytes = 0; 
      int receivebytes = 0; 
      byte[] receivebuffer = new byte[128]; 
      if((receivebytes=in.read(receivebuffer))!=-1) { 
        totalbytes += receivebytes; 
      } 
      string servermessage = new string(receivebuffer, 0, receivebytes); 
      system.out.println("client: receives servermessage->" + servermessage); 
    } catch (unknownhostexception e) { 
      e.printstacktrace(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } catch (exception e) { 
      e.printstacktrace(); 
    } finally { 
      try { 
        // 发送请求并接收到响应,通信完成,关闭连接 
        out.close(); 
        in.close(); 
        socket.close(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
  } 
 
  public static void main(string[] args) { 
    int n = 1; 
    stringbuffer data = new stringbuffer(); 
    date start = new date(); 
    for(int i=0; i<n; i++) { 
      data.delete(0, data.length()); 
      data.append("i am the client ").append(++pos).append("."); 
      simplebiotcpclient client = new simplebiotcpclient("localhost", 1983); 
      client.send(data.tostring().getbytes()); 
    } 
    date end = new date(); 
    long cost = end.gettime() - start.gettime(); 
    system.out.println(n + " requests cost " + cost + " ms."); 
  } 
} 

首先启动socket服务端进程simplebiotcpserver,然后再运行socket客户端simplebiotcpclient。可以看到,服务端接收到请求数据,然后响应客户端,客户端接收到了服务端的响应数据。

上述实现中,对于socket客户端和服务端都是一次写入,并一次读出,而在实际中如果每次通信过程中数据量特别大的话,服务器端是不可能接受的,可以在确定客户端请求数据字节数的情况,循环来读取并进行处理。

另外,对于上述实现中流没有进行装饰(wrapped)处理,在实际中会有性能的损失,如不能缓冲等。

对于socket服务端接收数据,如果可以使多次循环读取到的字节数据通过一个可变长的字节缓冲区来存储,就能方便多了,可是使用bytearrayoutputstream,例如:

bytearrayoutputstream data = new bytearrayoutputstream(); 
data.write(receivebuffer, totalbytes , totalbytes + receivebytes); 

bio通信测试

下面测试一下大量请求的场景下,socket服务端处理的效率。

第一种方式:通过for循环来启动5000个socket客户端,发送请求,代码如下所示:

public static void main(string[] args) { 
  int n = 5000; 
  stringbuffer data = new stringbuffer(); 
  date start = new date(); 
  for(int i=0; i<n; i++) { 
    data.delete(0, data.length()); 
    data.append("i am the client ").append(++pos).append("."); 
    simplebiotcpclient client = new simplebiotcpclient("localhost", 1983); 
    client.send(data.tostring().getbytes()); 
  } 
  date end = new date(); 
  long cost = end.gettime() - start.gettime(); 
  system.out.println(n + " requests cost " + cost + " ms."); 
} 

经过测试,大约需要9864ms,大概接近10s。

第二种方式:通过启动5000个独立的客户端线程,同时请求,服务端进行计数:

package org.shirdrn.java.communications.bio; 
 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.outputstream; 
import java.net.serversocket; 
import java.net.socket; 
import java.net.unknownhostexception; 
import java.util.date; 
 
/** 
 * 基于bio的socket通信测试 
 * 
 * @author shirdrn 
 */ 
public class simplebiotcptest { 
   
  static int threadcount = 5000; 
   
  /** 
   * 基于bio的socket服务端进程 
   * 
   * @author shirdrn 
   */ 
  static class socketserver extends thread { 
     
    /** 服务端口号 */ 
    private int port = 8888; 
    /** 为客户端分配编号 */ 
    private static int sequence = 0; 
     
    public socketserver(int port) { 
      this.port = port; 
    } 
     
    @override 
    public void run() { 
      socket socket = null; 
      int counter = 0; 
      try { 
        serversocket serversocket = new serversocket(this.port); 
        boolean flag = false; 
        date start = null; 
        while(true) { 
          socket = serversocket.accept(); // 监听 
          // 有请求到来才开始计时 
          if(!flag) { 
            start = new date(); 
            flag = true; 
          } 
          this.handlemessage(socket); // 处理一个连接过来的客户端请求 
          if(++counter==threadcount) { 
            date end = new date(); 
            long last = end.gettime() - start.gettime(); 
            system.out.println(threadcount + " requests cost " + last + " ms."); 
          } 
        } 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
     
    /** 
     * 处理一个客户端socket连接 
     * @param socket 客户端socket 
     * @throws ioexception 
     */ 
    private void handlemessage(socket socket) throws ioexception { 
      inputstream in = socket.getinputstream(); // 流:客户端->服务端(读) 
      outputstream out = socket.getoutputstream(); // 流:服务端->客户端(写) 
      int receivebytes; 
      byte[] receivebuffer = new byte[128]; 
      string clientmessage = ""; 
      if((receivebytes=in.read(receivebuffer))!=-1) { 
        clientmessage = new string(receivebuffer, 0, receivebytes); 
        if(clientmessage.startswith("i am the client")) { 
          string serverresponsewords =  
            "i am the server, and you are the " + (++sequence) + "th client."; 
          out.write(serverresponsewords.getbytes()); 
        } 
      } 
      out.flush(); 
      system.out.println("server: receives clientmessage->" + clientmessage); 
    } 
  } 
   
  /** 
   * 基于bio的socket客户端线程 
   * 
   * @author shirdrn 
   */ 
  static class socketclient implements runnable { 
     
    private string ipaddress; 
    private int port; 
    /** 待发送的请求数据 */ 
    private string data; 
     
    public socketclient(string ipaddress, int port) { 
      this.ipaddress = ipaddress; 
      this.port = port; 
    } 
 
    @override 
    public void run() { 
      this.send();       
    } 
     
    /** 
     * 连接socket服务端,并模拟发送请求数据 
     */ 
    public void send() { 
      socket socket = null; 
      outputstream out = null; 
      inputstream in = null; 
      try { 
        socket = new socket(this.ipaddress, this.port); // 连接 
        // 发送请求 
        out = socket.getoutputstream(); 
        out.write(data.getbytes());  
        out.flush(); 
        // 接收响应 
        in = socket.getinputstream(); 
        int totalbytes = 0; 
        int receivebytes = 0; 
        byte[] receivebuffer = new byte[128]; 
        if((receivebytes=in.read(receivebuffer))!=-1) { 
          totalbytes += receivebytes; 
        } 
        string servermessage = new string(receivebuffer, 0, receivebytes); 
        system.out.println("client: receives servermessage->" + servermessage); 
      } catch (unknownhostexception e) { 
        e.printstacktrace(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } catch (exception e) { 
        e.printstacktrace(); 
      } finally { 
        try { 
          // 发送请求并接收到响应,通信完成,关闭连接 
          out.close(); 
          in.close(); 
          socket.close(); 
        } catch (ioexception e) { 
          e.printstacktrace(); 
        } 
      } 
    } 
 
    public void setdata(string data) { 
      this.data = data; 
    } 
  } 
 
  public static void main(string[] args) throws exception { 
    socketserver server = new socketserver(1983); 
    server.start(); 
     
    thread.sleep(3000); 
     
    for(int i=0; i<threadcount; i++) { 
      socketclient client = new socketclient("localhost", 1983); 
      client.setdata("i am the client " + (i+1) + "."); 
      new thread(client).start(); 
      thread.sleep(0, 1); 
    }     
  } 
}

 经过测试,大约需要7110ms,大概接近7s,没有太大提高。

bio通信改进

通过上面的测试我们可以发现,在socket服务端对来自客户端的请求进行处理时,会发生阻塞,严重地影响了能够并发处理请求的效率。实际上,在socket服务端接收来自客户端连接能力的范围内,可以将接收请求独立出来,从而在将处理请求独立粗话来,通过一个请求一个线程处理的方式来解决上述问题。这样,服务端是多处理线程对应客户端多请求,处理效率有一定程度的提高。

下面,通过单线程接收请求,然后委派线程池进行多线程并发处理请求:

/** 
   * 基于bio的socket服务端进程 
   * 
   * @author shirdrn 
   */ 
  static class socketserver extends thread { 
     
    /** 服务端口号 */ 
    private int port = 8888; 
    /** 为客户端分配编号 */ 
    private static int sequence = 0; 
    /** 处理客户端请求的线程池 */ 
    private executorservice pool; 
     
    public socketserver(int port, int poolsize) { 
      this.port = port; 
      this.pool = executors.newfixedthreadpool(poolsize); 
    } 
     
    @override 
    public void run() { 
      socket socket = null; 
      int counter = 0; 
      try { 
        serversocket serversocket = new serversocket(this.port); 
        boolean flag = false; 
        date start = null; 
        while(true) { 
          socket = serversocket.accept(); // 监听 
          // 有请求到来才开始计时 
          if(!flag) { 
            start = new date(); 
            flag = true; 
          } 
          // 将客户端请求放入线程池处理 
          pool.execute(new requesthandler(socket)); 
          if(++counter==threadcount) { 
            date end = new date(); 
            long last = end.gettime() - start.gettime(); 
            system.out.println(threadcount + " requests cost " + last + " ms."); 
          } 
        } 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
     
    /** 
     * 客户端请求处理线程类 
     * 
     * @author shirdrn 
     */ 
    class requesthandler implements runnable { 
 
      private socket socket; 
       
      public requesthandler(socket socket) { 
        this.socket = socket; 
      } 
       
      @override 
      public void run() { 
        try { 
          inputstream in = socket.getinputstream(); // 流:客户端->服务端(读) 
          outputstream out = socket.getoutputstream(); // 流:服务端->客户端(写) 
          int receivebytes; 
          byte[] receivebuffer = new byte[128]; 
          string clientmessage = ""; 
          if((receivebytes=in.read(receivebuffer))!=-1) { 
            clientmessage = new string(receivebuffer, 0, receivebytes); 
            if(clientmessage.startswith("i am the client")) { 
              string serverresponsewords =  
                "i am the server, and you are the " + (++sequence) + "th client."; 
              out.write(serverresponsewords.getbytes()); 
            } 
          } 
          out.flush(); 
          system.out.println("server: receives clientmessage->" + clientmessage); 
        } catch (ioexception e) { 
          e.printstacktrace(); 
        }         
      } 
    } 
  } 

可见,这种改进方式增强服务端处理请求的并发度,但是每一个请求都要由一个线程去处理,大量请求造成服务端启动大量进程进行处理,也是比较占用服务端资源的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。