前言
`使用window系统环境
- window 环境测试
- 测试使用telnet ip 端口
- win+R
- cmd 输入telnet id port
- Ctrl+]
- send 发送信息
缺点:无阻塞 但是cpu空转 无效遍历
一、代码撸上
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class NioService {
//保存客户端连接
static List<SocketChannel> channelList = new ArrayList<>();
/***
* window 环境测试
* 测试使用telnet ip 端口
* win+R cmd
* 输入telnet id port
* Ctrl+]
* send 发送信息
* 无阻塞 但是cpu空转 无效遍历
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 创建 NIO ServerSocketChannel,与 BIO ServerSocket 类似
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(8080));
// 设置 ServerSocketChannel 为非阻塞
serverSocket.configureBlocking(false);
System.out.println("---web---starter");
while (true) {
// 非阻塞模式 accept 方法不会阻塞,否则会阻塞
// NIO 的非阻塞是由操作系统内部实现的,底层调用了 Linux 内核的 accept 函数
SocketChannel socketChannel = serverSocket.accept();
// 如果有客户端进行连接
if (socketChannel != null) {
System.out.println("---link---success--");
// 设置 SocketChannel 为非阻塞
socketChannel.configureBlocking(false);
// 保存客户端连接在 List 中
channelList.add(socketChannel);
}
// 遍历连接进行数据读取
Iterator<SocketChannel> iterator = channelList.iterator();
while (iterator.hasNext()) {
SocketChannel sc = iterator.next();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
// 非阻塞模式 read 方法不会阻塞,否则会阻塞
int len = sc.read(byteBuffer);
// 如果有数据,把数据打印出来
if (len > 0) {
System.out.println("msgData:" + new String(byteBuffer.array(), 0, len));
} else if (len == -1) {
//当连接客户端 断开连接的时候返回值为 -1,没有传数据是 0
iterator.remove(); //这句话是移除当前序列
System.out.println("---unlink--success--");
}
}
}
}
}