标签:scan 优先 执行 accept bre lan _id 断开连接 nts
import java.net.*; import java.io.*; public class SocketServiceTest { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(10002); Socket socket = null; try { while (true) { socket = serverSocket.accept(); System.out.println("socket连接:" + socket.getRemoteSocketAddress().toString()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); while(true) { String readLine = in.readLine(); System.out.println("收到消息" + readLine); if("end".equals(readLine)) break; } } } catch (SocketException se) { System.out.println("client断开连接"); } catch (IOException e) { e.printStackTrace(); } finally { System.out.println("socket关闭:" + socket.getRemoteSocketAddress().toString()); socket.close(); } } }
(为什么jfsdkof 没有显示出来?
自己想)
import java.net.*; import java.io.*; import java.util.Scanner; public class MultithreadJIoSocketTest { public static void main (String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(10002); Thread thread = new Thread(new Accptor(serverSocket)); thread.start(); } } import java.io.*; import java.net.*; public class Accptor implements Runnable { private ServerSocket serverSocket; public Accptor(ServerSocket serverSocket) { this.serverSocket = serverSocket; } public void run() { while (true) { Socket socket = null; try { socket = serverSocket.accept(); if(socket != null) { System.out.println("收到了socket:" + socket.getRemoteSocketAddress().toString()); Thread thread = new Thread(new Processor(socket)); thread.start(); } } catch (IOException e) { e.printStackTrace(); } } } } import java.io.*; import java.net.*; public class Processor implements Runnable { private Socket socket; public Processor(Socket socket) { this.socket = socket; } public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String readLine; while(true) { readLine = in.readLine(); System.out.println("收到消息" + readLine); if("end".equals(readLine)) { break; } //client断开连接 Thread.sleep(5000); } } catch (InterruptedException e) { e.printStackTrace(); } catch (SocketException se) { System.out.println("client断开连接"); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
至少上面的三个问题都说明,我们须要一种新的io方式!
OK,下一章我们再说nio
标签:scan 优先 执行 accept bre lan _id 断开连接 nts
原文地址:http://www.cnblogs.com/liguangsunls/p/7201878.html