客户端非阻塞式通信(Java Socket Channel)

客户端非阻塞式通信(Java Socket Channel) 服务端代码阻塞式import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; /** * 服务器端阻塞式IOJava ServerSocket * author Bright Lee */ public class ServerSocketTest { public static void main(String[] args) { ServerSocket serverSocket null; Socket socket null; InputStream in null; try { serverSocket new ServerSocket(6666); socket serverSocket.accept(); SocketAddress clientAddress socket.getRemoteSocketAddress(); System.out.println(有客户端连接 clientAddress); in socket.getInputStream(); int value -1; while ((value in.read()) ! -1) { char ch (char) value; System.out.print(ch); } } catch (Exception e) { e.printStackTrace(); } finally { close(serverSocket, socket, in); } } private static void close(ServerSocket serverSocket, Socket socket, InputStream in) { try { if (in ! null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (socket ! null) { socket.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (serverSocket ! null) { serverSocket.close(); } } catch (Exception e) { e.printStackTrace(); } } }客户端代码非阻塞式import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; /** * 客户端非阻塞式IOJava SocketChannel * author Bright Lee */ public class SocketChannelTest { public static void main(String[] args) { ByteBuffer buffer ByteBuffer.allocate(1024); SocketChannel socketChannel null; try { socketChannel SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(127.0.0.1, 6666)); if (socketChannel.finishConnect()) { String info Im a client! My number is System.currentTimeMillis(); buffer.clear(); buffer.put(info.getBytes(UTF-8)); buffer.flip(); while (buffer.hasRemaining()) { socketChannel.write(buffer); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (socketChannel ! null) { socketChannel.close(); } } catch (Exception e) { e.printStackTrace(); } } } }先运行服务端代码ServerSocketTest.java再运行客户端代码SocketChannelTest.java服务端打印信息如下有客户端连接/127.0.0.1:51564I’m a client! My number is 1547276873269青蛙客服系统https://download.csdn.net/download/look4liming/93326820