实验 6 非阻塞通信
一、实验目的
1. 掌握非阻塞编程。
2. 掌握 java.nio 包中的类 ServerSocketChannel,SocketChannel,Selector,SelectionKey 和
ByteBuffer 的用法。
二、实验内容
对实验 5 中第二个实验题目对服务器端程序采用:由一个线程负责接收多个客户连接,
采用阻塞模式;由另一个线程负责与多个客户交换数据,采用非阻塞模式。对客户端采
用非阻塞通信。
三、设计思路
实例化 HashMap 类型的一个对象用来存放每一个客户对应的套接字和通道,实例化
线程通道选择器等,当由用户请求时,接受,加入选择项,注册感兴趣事件,另一线程处理
输入流,在前面加 echo:,发给客户端。
四、程序清单
import java.nio.channels.*;
import java.nio.charset.*;
import java.nio.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class NBlockingServer {
int port = 8000;
int BUFFERSIZE = 1024;
Selector selector = null;
ServerSocketChannel serverChannel = null;
HashMap clientChannelMap = null; //用来存放每一个客户连接对应的套接字和
通道
public NBlockingServer(int port) {
this.clientChannelMap = new HashMap();
this.port = port;
}
//throws IOException
public void initialize() {
//初始化,分别实例化一个选择器,一个服务器端可选择通道
try {
this.selector = Selector.open();
this.serverChannel = ServerSocketChannel.open();
this.serverChannel.configureBlocking(false);
InetAddress localhost = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(localhost, this.port);
this.serverChannel.socket().bind(isa); //将该套接字绑定到服务器某一可用端
口 }
catch (IOException ex) {