文章目录
NIO之同步阻塞模式前言一、POM包引入二、服务端接受消息
2.1 服务端代码2.2 客户端代码 三、服务端推送消息
3.1 服务端代码3.2 客户端代码 总结
前言
为了深入理解java中NIO的同步非阻塞功能,本文从同步阻塞模式开始,开发了服务端接受消息和推送消息的Demo,以便后续学习同步非阻塞模式打下基础。
一、POM包引入
二、服务端接受消息 2.1 服务端代码org.projectlombok lombok 1.18.10 com.google.code.gson gson 2.8.5 ch.qos.logback logback-classic 1.2.3
代码如下(示例):
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
ByteBuffer buffer = ByteBuffer.allocate(1024);
log.info("Connecting...");
SocketChannel channel = serverSocketChannel.accept();
log.info("Connected, channel={}", channel);
while(true) {
log.info("Before read, channel={}", channel);
channel.read(buffer);
buffer.flip();
show(buffer);
buffer.clear();
log.info("After read, channel={}", channel);
}
}
2.2 客户端代码
代码如下(示例):
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress("localhost", 8080));
channel.write(Charset.defaultCharset().encode("Hello worldn"));
channel.write(Charset.defaultCharset().encode("My name is lein"));
channel.close();
}
三、服务端推送消息
3.1 服务端代码
代码如下(示例):
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
log.info("Connecting...");
SocketChannel channel = serverSocketChannel.accept();
log.info("Connected, channel={}", channel);
channel.write(Charset.defaultCharset().encode("Hi"));
channel.close();
}
3.2 客户端代码
代码如下(示例):
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress("localhost", 8080));
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(true) {
channel.read(buffer);
buffer.flip();
show(buffer);
buffer.clear();
}
}
总结
以上从服务端接受消息和服务端推送消息的两个例子可以看出服务端同一时间只能和一个客户端建立连接并实现通信,下一章节将实现同步非阻塞模式的通信方式以作对比。



