服务端
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class ChatServer {
public ChatServer(){
}
public void start() throws IOException {
//获取服务端通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
System.out.println("服务器启动");
//设为非阻塞状态
serverSocketChannel.configureBlocking(false);
//设置端口号
serverSocketChannel.bind(new InetSocketAddress(6666));
//获取选择器
Selector selector = Selector.open();
//将通道注册进选择器
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//遍历选择器,如果大于0,说明有用户连接
while (selector.select() > 0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
//如果是连接状态
if (selectionKey.isAcceptable()) {
//获取客户端通道,并设为非阻塞状态注册进选择器
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer allocate = ByteBuffer.allocate(1024);
int len = 0;
while ((len = channel.read(allocate)) > 0) {
allocate.flip();
String msg = new String(allocate.array());
System.out.println(serverSocketChannel.getLocalAddress()+"客户端消息:"+msg);
allocate.clear();
}
}
}
//必须移除,否则会一直进行已经处理的事件
iterator.remove();
}
}
}
客户端
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class ChatClient {
public ChatClient(){
}
public void start() throws IOException {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",6666));
socketChannel.configureBlocking(false);
ByteBuffer allocate = ByteBuffer.allocate(1024);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String msg = scanner.next();
allocate.put(msg.getBytes());
allocate.flip();
socketChannel.write(allocate);
allocate.clear();
}
int len = 0;
while ((len = socketChannel.read(allocate)) > 0){
allocate.flip();
System.out.println("服务端:"+new String(allocate.array()));
allocate.clear();
}
socketChannel.close();
}
}
效果

915

被折叠的 条评论
为什么被折叠?



