聊天程序java代码 java编一个聊天室代码和结果( 二 )


if(n0){
byteBuffer.flip();
charBuffer = decoder.decode(byteBuffer);
msg = charBuffer.toString();
ta.append(msg + "\n");
}
byteBuffer.clear();
Thread.sleep(500);
}
}catch(Exception e){
e.printStackTrace();
System.exit(0);
}
}
}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
import java.util.*;
public class ICQServer {
private Selector selector = null;
private ServerSocketChannel ssc = null;
//服务器端通信端口号
private int port = 8814;
//在线用户列表
private HashtableString, SocketChannel userList = null;
public ICQServer() {}
public ICQServer(int port) {
this.port = port;
}
//初始化服务器
public void init() {
try {
//创建选择器对象
selector = Selector.open();
//创建ServerSocketChannel
ssc = ServerSocketChannel.open();
//设置ServerSocketChannel为非阻塞模式
ssc.configureBlocking(false);
InetAddress ip = InetAddress.getLocalHost();
System.out.println("主机地址 -------- " + ip);
InetSocketAddress isa = new InetSocketAddress(ip, port);
//将与本通道相关聊天程序java代码的服务器套接字对象绑定到指定地址和端口
ssc.socket().bind(isa);
//创建在线用户列表
userList = new HashtableString, SocketChannel ();
}
catch (IOException e) {
System.out.println("初始化服务器时异常聊天程序java代码,原因--------" + e.getMessage());
}
}
//启动服务器
public void start() {
try {
//将ServerSocketChannel注册到Selector上聊天程序java代码 , 准备接收新连接请求
SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
SocketChannel sc;
int n;
String name; //用户名
String msg; //用户发言信息
while (true) {
//选择当前所有处于就绪状态聊天程序java代码的通道所对应的选择键,并将这些键组成已选择键集
n = selector.select(); //n为已选择键集中键的个数
if (n0) {
//获取此选择器的已选择键集 。
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
//遍历当前已选择键集
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
//从当前已选择键集中移除当前键,避免重复处理
it.remove();
//如果当前键对应的通道已准备好接受新的套接字连接
if (key.isAcceptable()) {
//获取当前键对应的可选择通道(ServerSocketChannel)
ssc = (ServerSocketChannel) key.channel();
//接收新的套接字连接请求,返回新建的SocketChannel
sc = (SocketChannel) ssc.accept();
//如果有新用户接入
if (sc != null) {
//接收新上线用户姓名
name = readMessage(sc);
//设置新建的SocketChannel为非阻塞模式
sc.configureBlocking(false);
//将新建的SocketChannel注册到Selector上,准备进行数据"写"操作,
//并将当前用户名以附件的方式附带记录到新建的选择键上 。
SelectionKey newKey = sc.register(selector,
SelectionKey.OP_WRITE, name);
//将新上线用户信息加入到在线用户列表
userList.put(name, sc);
//发送"新用户上线"通知
transmitMessage(name + " in!", "--Server Info--");
}
}
//否则,如果当前键对应的通道已准备好进行"写"操作
else if (key.isWritable()) {
//获取当前键对应的可选择通道(SocketChannel)
sc = (SocketChannel) key.channel();
//接收该通道相应用户的发言信息
msg = readMessage(sc);
//获取选择键上附带记录的当前用户名

推荐阅读