使用线程池实现服务器端,可以支持同一时间多个客户端发起的请求
1 package demo.soket.tcp; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.net.ServerSocket; 6 import java.net.Socket; 7 import java.util.concurrent.ExecutorService; 8 import java.util.concurrent.Executors; 9 10 public class TcpService1 { 11 12 public static void main(String args[]) { 13 System.out.println("tcp服务器启动......"); 14 //创建可缓存的线程池 15 ExecutorService executor=Executors.newCachedThreadPool(); 16 ServerSocket service=null; 17 try { 18 //创建服务器连接 19 service=new ServerSocket(8080); 20 while(true) { 21 final Socket accept=service.accept();//阻塞 22 executor.execute(new Runnable() { 23 public void run() { 24 try { 25 InputStream in = accept.getInputStream(); 26 //将字节流转换为字符串 27 byte[] b=new byte[1024]; 28 int len=in.read(b); 29 String str=new String(b,0,len); 30 System.out.println("服务器接收客户端内容:"+str); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 } 34 35 } 36 }); 37 38 } 39 } catch (IOException e) { 40 e.printStackTrace(); 41 }finally { 42 if(service!=null) { 43 try { 44 service.close(); 45 } catch (IOException e) { 46 e.printStackTrace(); 47 } 48 } 49 } 50 } 51 52 }
客服端一:
package demo.soket.tcp; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class TcpClient1 { public static void main(String[] args) { try { Socket client=new Socket("127.0.0.1", 8080); OutputStream os=client.getOutputStream(); os.write("我是客户端一".getBytes()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
客服端二:
package demo.soket.tcp; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class TcpClient2 { public static void main(String[] args) { try { Socket client=new Socket("127.0.0.1", 8080); OutputStream os=client.getOutputStream(); os.write("我是客户端二".getBytes()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
浏览器模拟客户端三:
原文:https://www.cnblogs.com/KdeS/p/13434596.html