Spring中的aware接口详情
231
2022-09-13
Java基于NIO实现聊天室功能
本文实例为大家分享了java基于NIO实现聊天室功能的具体代码,供大家参考,具体内容如下
Sever端
package com.qst.one;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.Channel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.nio.ByteBuffer;
public class Server {
private static SocketChannel accept;
public static void main(String[] args) {
System.out.println("----服务端启动---");
try {
// 获取通道
ServerSocketChannel channel = ServerSocketChannel.open();
// 配置非阻塞模式
channel.configureBlocking(fsLAWlalse);
// 绑定连接的端口
channel.bind(new InetSocketAddress(9999));
// 获取选择器
Selector selector = Selector.open();
// 注册通道到选择器上,开始监听事件
channel.register(selector, SelectionKey.OP_ACCEPT);
// 使用选择器进行轮询
while (selector.select() > 0) {
// 获取到选择器上所有注册的通道中已经就绪好的事件
Iterator
while (iterator.hasNext()) {
// 获取事件
SelectionKey next = iterator.next();
// 判断事件类型
if (next.isAcceptable()) {
// 获取通道
accept = channel.accept();
// 获取当前连接分配地址
SocketAddress address = accept.getLocalAddress();
System.out.println(address + "上线了");
// 切换模式
accept.configureBlocking(false);
// 将通道注册到选择器上
accept.register(selector, SelectionKey.OP_READ);
}
// 如果为读模式
else if (next.isReadable()) {
SocketChannel accept = (SocketChannel) next.channel();
// 读取事件
ByteBuffer buffer = ByteBuffer.allocate(1024);
int len;
while ((len = accept.read(buffer)) > 0) {
// 开启读模式
buffer.flip();
// System.out.println((char)len);
System.out.println(new String(buffer.array(), 0, len));
// 归位
buhttp://ffer.clear();
}
}
iterator.remove();
}
}
} catch (Exception e) {
try {
SocketAddress address = accept.getRemoteAddress();
System.out.println(address+"离线了");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Client端
package com.qst.one;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.nio.ByteBuffer;
public class Client {
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 9999));
channel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
Scanner sc = new Scanner(System.in);
SocketAddress address = channel.getLocalAddress();
System.out.println(address+"ready~~~");
while(true) {
System.out.print("tim:");
String name = sc.nextLine();
buffer.put(("tim :"+name).getBytes());
buffer.flip();
channel.write(buffer);
buffer.clear();
}
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~