服务器
public static void main(String[] args) {
System.out.println("服务器已启动,等待连接......");
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 设置非阻塞
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress(8095));
SocketChannel socketChannel;
while (true) {
socketChannel = serverSocketChannel.accept();
if (null != socketChannel) {
socketChannel.configureBlocking(false);
String message = "已成功与【服务器】建立连接";
// 向客户端发送消息
socketChannel.write(ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)));
InetSocketAddress inetSocketAddress = (InetSocketAddress) socketChannel.getRemoteAddress();
System.out.println("【客户端】:" + inetSocketAddress.getPort() + "已连接");
byte[] bytes = new byte[1024];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
int length = 0;
try {
while (true) {
if ((length = socketChannel.read(byteBuffer)) != 0) {
String clientMsg = new String(byteBuffer.array(), 0, length, StandardCharsets.UTF_8);
System.out.println("【客户端】:" + clientMsg);
message = "【服务器】已成功接收消息:" + clientMsg;
socketChannel.write(ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)));
byteBuffer.clear();
}
}
} catch (IOException e) {
e.printStackTrace();
socketChannel.close();
System.out.println("【客户端】:" + inetSocketAddress.getPort() + "已断开连接。");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
客户端
public static void main(String[] args) {
System.out.println("客户端已启动,正在连接......");
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("localhost", 8095));
Scanner scanner = new Scanner(System.in);
byte[] bytes = new byte[1024];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
int length = 0;
while (true) {
if (socketChannel.isOpen()) {
// 在非阻塞模式下connect也是非阻塞的,所以要确保连接已经建立完成
if (socketChannel.finishConnect()) {
length = socketChannel.read(byteBuffer);
if (length > 0) {
System.out.println(new String(byteBuffer.array(), 0, length));
}
byteBuffer.clear();
System.out.print("【客户端】:");
String message = scanner.nextLine();
byteBuffer.put(message.getBytes(StandardCharsets.UTF_8));
byteBuffer.flip();
socketChannel.write(byteBuffer);
byteBuffer.clear();
Thread.sleep(1);
}
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}