Java NIO实战之多人聊天室
短信预约 -IT技能 免费直播动态提醒
本文实例为大家分享了Java NIO实战之多人聊天室的具体代码,供大家参考,具体内容如下
NIO服务端
public class NioServer {
public void start() throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8000));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("服务器启动成功!");
for (;;) { // while(true) c for;;
int readyChannels = selector.select();
if (readyChannels == 0) continue;
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = (SelectionKey) iterator.next();
iterator.remove();
if (selectionKey.isAcceptable()) {
acceptHandler(serverSocketChannel, selector);
}
if (selectionKey.isReadable()) {
readHandler(selectionKey, selector);
}
}
}
}
private void acceptHandler(ServerSocketChannel serverSocketChannel,
Selector selector)
throws IOException {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
socketChannel.write(Charset.forName("UTF-8")
.encode("你与聊天室里其他人都不是朋友关系,请注意隐私安全"));
}
private void readHandler(SelectionKey selectionKey, Selector selector)
throws IOException {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
String request = "";
while (socketChannel.read(byteBuffer) > 0) {
byteBuffer.flip();
request += Charset.forName("UTF-8").decode(byteBuffer);
}
socketChannel.register(selector, SelectionKey.OP_READ);
if (request.length() > 0) {
// 广播给其他客户端
broadCast(selector, socketChannel, request);
}
}
private void broadCast(Selector selector,
SocketChannel sourceChannel, String request) {
Set<SelectionKey> selectionKeySet = selector.keys();
selectionKeySet.forEach(selectionKey -> {
Channel targetChannel = selectionKey.channel();
// 剔除发消息的客户端
if (targetChannel instanceof SocketChannel
&& targetChannel != sourceChannel) {
try {
// 将信息发送到targetChannel客户端
((SocketChannel) targetChannel).write(
Charset.forName("UTF-8").encode(request));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) throws IOException {
new NioServer().start();
}
}
NIO客户端
public class NioClient {
public void start(String nickname) throws IOException {
SocketChannel socketChannel = SocketChannel.open(
new InetSocketAddress("127.0.0.1", 8000));
// 新开线程,专门负责来接收服务器端的响应数据
// selector , socketChannel , 注册
Selector selector = Selector.open();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
new Thread(new NioClientHandler(selector)).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String request = scanner.nextLine();
if (request != null && request.length() > 0) {
socketChannel.write(
Charset.forName("UTF-8")
.encode(nickname + " : " + request));
}
}
}
public static void main(String[] args) throws IOException {
// new NioClient().start();
}
}
客户端线程,处理服务器端响应的的消息
public class NioClientHandler implements Runnable {
private Selector selector;
public NioClientHandler(Selector selector) {
this.selector = selector;
}
@Override
public void run() {
try {
for (;;) {
int readyChannels = selector.select();
if (readyChannels == 0) continue;
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = (SelectionKey) iterator.next();
iterator.remove();
if (selectionKey.isReadable()) {
readHandler(selectionKey, selector);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void readHandler(SelectionKey selectionKey, Selector selector)
throws IOException {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
String response = "";
while (socketChannel.read(byteBuffer) > 0) {
byteBuffer.flip();
response += Charset.forName("UTF-8").decode(byteBuffer);
}
socketChannel.register(selector, SelectionKey.OP_READ);
if (response.length() > 0) {
System.out.println(response);
}
}
}
我们定义三个客户端,模拟三个用户在聊天室发送消息
public class AClient {
public static void main(String[] args)
throws IOException {
new NioClient().start("AClient");
}
}
public class BClient {
public static void main(String[] args)
throws IOException {
new NioClient().start("BClient");
}
}
public class CClient {
public static void main(String[] args)
throws IOException {
new NioClient().start("CClient");
}
}
NIO 聊天室到此结束
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341