package nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
public class ChatSer {
Selector selector;
ServerSocketChannel serChannel;
public ChatSer() throws IOException {
serChannel = ServerSocketChannel.open();
serChannel.socket().bind(new InetSocketAddress(6767));
serChannel.configureBlocking(false);
selector = Selector.open();
serChannel.register(selector, SelectionKey.OP_ACCEPT);
listen();
}
private void listen() throws IOException {
while (true) {
int num = selector.select();
if (num > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey next = iterator.next();
if(next.isAcceptable()){
SocketChannel channel = serChannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
System.out.println(channel.getRemoteAddress()+":来了");
}
if (next.isReadable()) {
read(next);
}
iterator.remove();
}
}
}
}
private void read(SelectionKey next) {
SocketChannel channel=null;
try {
channel = (SocketChannel) next.channel();
// ByteBuffer buf = (ByteBuffer) next.attachment();
ByteBuffer buf = ByteBuffer.allocate(1234);
int count = channel.read(buf);//按照实际的
if (count>0) {
String msg = new String(buf.array(), 0, count);
System.out.println("client:"+msg);
copy(msg,channel);
}
} catch (IOException e) {
try {
System.out.println(channel.getRemoteAddress()+"走了。。。。。。。。。");
next.cancel();
channel.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
private void copy(String msg, SocketChannel next) throws IOException {
System.out.println("begin copy to others");
Set<SelectionKey> keys = selector.keys();
System.out.println("keys.size() = " + keys.size());
for (SelectionKey key : keys) {
SelectableChannel channel = key.channel();
if (channel instanceof SocketChannel&&channel!=next) {
System.out.println("----------+++++++++");
SocketChannel other = (SocketChannel) channel;
ByteBuffer buf = ByteBuffer.wrap(msg.getBytes());
other.write(buf);
}
}
}
public static void main(String[] args) throws IOException {
ChatSer chatSer = new ChatSer();
chatSer.listen();
}
}
004NIO服务端
最新推荐文章于 2023-06-21 08:53:55 发布