java nio
一、服务器
1、初始化
(1)创建多路复用器selector
(2)创建服务器socket管道serversSocketChannel
(3)serversocket绑定服务端口
(4)设置服务器socket管道的阻塞方式为非阻塞式
(5)为服务器socket管道绑定selector
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
2、端口监听和处理
(1)监听多路复用器selector
(2)获取客户端请求状态集selectedKeys
(3)循环处理每笔请求,判断每笔请求的状态并根据状态做相应处理
while (true) {
int n = selector.select();//监听多路复用器,看是否有客户端请求
if (n <= 0)
continue;
Iterator<SelectionKey> it = selector.selectedKeys().iterator();//获取客户端请求状态集
while (it.hasNext()) {
SelectionKey key = it.next();
//System.out.print(".");
if (key.isAcceptable()) {//如果状态为acceptable,则为新连接
SocketChannel channel = ((ServerSocketChannel) key
.channel()).accept();//获取socket管道
if (channel != null) {
// new connection from client, register it
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
/**
*/自定义处理逻辑
*/
*/
}
if (key.isReadable()) {//如果状态为Readable,则该已建立连接,读取请求内容
SocketChannel channel = (SocketChannel) key.channel();
m_buffer.clear(); // empty the buffer
while ((count = channel.read(m_buffer)) > 0) {
//读取请求流并作处理
}
if (count < 0) {//如果出现socket关闭标示,则关闭管道
// Close channel on EOF.
channel.close();
}
}
it.remove();//请求处理完后清除请求集
}
}
二、客户端
以任何方式发起TCP连接和请求即可