When the socket chat rooms on the client results in blocking solution appears readline

Client:

	  String val=req.getParameter("text").toString();
		  String id=req.getParameter("id");
		  Socket socket =null; 
		  if(id==null||id.equals("")){
			  socket= new Socket("127.0.0.1",8090);
			  id=socketFactory.getNewId()+"";
			  socketFactory.add(Integer.parseInt(id), socket);
		  }else{
			  socket=socketFactory.get(Integer.parseInt(id));
			
		  }
		  OutputStream os=socket.getOutputStream();
		  //向页面传递
		  PrintWriter write=new PrintWriter(resp.getOutputStream());
		  write.write(id);

		  //向服务端传递
		  PrintWriter swrite=new PrintWriter(os);
		  swrite.println("i am client"+id+":"+val);
 	   	  write.close();
// 		 swrite.close();
// 	     	os.close();
//		  os.flush();
		  swrite.flush();
//		  write.flush();


 

Server:

		 ServerSocket serversocket=new ServerSocket(8090);
		 for(int i=0;i<10;i++){
		 Socket socket=serversocket.accept();
		 System.out.println("获取到请求"); 
		 BufferedReader bread=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		 StringBuilder msg=new StringBuilder();
		 String str=null;
		 while((str=bread.readLine())!=null&&str.length()>0){
			msg.append(str);
		 }
		 
     
		  System.out.print(msg);
		  PrintWriter write= new PrintWriter(socket.getOutputStream());
		  write.write("您好 我是服务端");  //服务端回应
		  write.flush();
		 }

Because we want to achieve while maintaining socket connection state, to achieve the server and client communicate with each other, and found that, when the service receives socket to read data, found that the situation in blocking readline at the rear by querying the data found in readline after receiving the end signal it will stop reading data, which means that the client calls close () or shutdownOutput (only) when can the current readline () stops. Solution

1, each receive only one call readline (without while loop)

2, using the read () method, a one-time increase buff memory data read out of the

3, the establishment of thread for a socket, after the server modify the code as follows

 

 ServerSocket serversocket=new ServerSocket(8090);
   ExecutorService exec=Executors.newCachedThreadPool();
   for(int i=0;i<10;i++){
   Socket socket=serversocket.accept();
   exec.execute(new Runnable() {  //启用线程
   
   @Override
   public void run() {
    // TODO Auto-generated method stub

     System.out.println("获取到请求"); 
     BufferedReader bread;
    try {
     bread = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      
      String str=null;
      while((str=bread.readLine())!=null){
       
        System.out.println(str);
      }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  });
    PrintWriter write= new PrintWriter(socket.getOutputStream());
    write.write("您好 我是服务端");  //服务端回应
    write.flush();
   }


 

 


 

Guess you like

Origin blog.csdn.net/mxy88888/article/details/71629857