Server 端,主要代码,这里 ServerSocketChannel 采用非阻塞模式,消息均不超过 1024 字节
public class Server{ public static void main(String[] arg) { try (ServerSocketChannel ssc = ServerSocketChannel.open()) { ssc.configureBlocking(false); ssc.bind(new InetSocketAddress("localhost", 9999)); System.out.println("启动成功 ..."); String msg = "server message "; while (true) { ByteBuffer byteBuffer = ByteBuffer.allocate(1024); try (SocketChannel sc = ssc.accept()) { if (null == sc) { log.info("空轮询 ..."); Thread.sleep(2000); continue; } while (true) { byteBuffer.put((msg + System.currentTimeMillis()).getBytes()); byteBuffer.flip(); sc.write(byteBuffer); byteBuffer.clear(); if (sc.read(byteBuffer) > 0) { System.out.println(new String(byteBuffer.array(), 0, byteBuffer.position())); byteBuffer.clear(); } Thread.sleep(1000); } } catch (Exception e) { log.info("处理请求时异常 !!!"); } } } catch (Exception e) { log.error("异常关闭 !!!"); } } }
Client 端,主要代码
@Slf4j(topic = "c.Client") public class Client { public static void main(String[] args) { try (SocketChannel sc = SocketChannel.open()) { sc.bind(new InetSocketAddress(8888)); sc.connect(new InetSocketAddress("localhost", 9999)); ByteBuffer byteBuffer = ByteBuffer.allocate(200); while (sc.read(byteBuffer) > 0) { byteBuffer.flip(); System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit())); sc.write(byteBuffer); byteBuffer.clear(); } } catch (Exception e) { log.error("异常关闭 !!!"); } } }