服務(wù)端
public class NioServer {
public static void main(String[] args) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
ArrayList<SocketChannel> socketChannels = new ArrayList<>();
ssc.bind(new InetSocketAddress(8888));
while (true) {
ssc.configureBlocking(false);
System.out.println("before accept");
SocketChannel socketChannel = ssc.accept();
if (socketChannel != null) {
socketChannels.add(socketChannel);
}
for (SocketChannel socketChannel1 : socketChannels) {
socketChannel1.configureBlocking(false);
System.out.println("before reading");
int read = socketChannel1.read(byteBuffer);
if (read > 0) {
byteBuffer.flip();
String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
byteBuffer.clear();
System.out.println(s);
}
}
}
} catch (IOException e) {
}
}
}