实例说明java
实例代码:编程
public class BIOServer { public static void main(String[] args) throws Exception { //一、建立一个线程池 ExecutorService threadPool = Executors.newCachedThreadPool(); ServerSocket serverSocket = new ServerSocket(6666); System.out.println("服务器启动了!!!"); while (true){ //监听,等待客户端链接 final Socket socket = serverSocket.accept(); System.out.println("链接到一个客户端"); //二、若是有客户端链接了,就建立一个线程,与之通信(单独写一个方法) threadPool.execute(new Runnable() { public void run() { //与客户端进行通信 handler(socket); } }); } } //编写一个与客户端通信的handler方法 public static void handler(Socket socket){ //用于接收数据 byte[] bytes = new byte[1024]; //经过socket获取输入流 InputStream inputStream = null; try { System.out.println("线程id="+Thread.currentThread().getId()+"名字="+Thread.currentThread().getName()); inputStream = socket.getInputStream(); //循环读取客户端发送的数据 while(true){ int read = inputStream.read(bytes); if (read!=-1){ //输出客户端发送的数据 System.out.println(“收到信息:”+new String(bytes,0,read)); }else{ break; } } } catch (IOException e) { e.printStackTrace(); }finally { System.out.println("关闭与客户端的链接......"); try { inputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
测试结果:服务器
服务器启动了!!! 链接到一个客户端 线程id=12名字=pool-1-thread-1 收到消息:nihao