IO的阻塞与非阻塞、同步与异步以及Java网络IO交互方式(5)
- UID
- 1029342
- 性别
- 男
|
IO的阻塞与非阻塞、同步与异步以及Java网络IO交互方式(5)
public class MultithreadJIoSocketTest{ @Test public void testMultithreadJIoSocket() throws Exception { ServerSocket serverSocket = new ServerSocket(10002); Thread thread = new Thread(new Accptor(serverSocket)); thread.start(); Scanner scanner = new Scanner(System.in); scanner.next(); } 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(); } } } } public class Processor implements Runnable { private Socket socket; public Processor(Socket socket) { this.socket = socket; } @Override 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; } //客户端断开连接 socket.sendUrgentData(0xFF); Thread.sleep(5000); } } catch (InterruptedException e) { e.printStackTrace(); } catch (SocketException se) { System.out.println("客户端断开连接"); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }} |
|
|
|
|
|