java nio SocketChannel 服务器端与多客户端 信息交互(聊天功能)(二)
String()+":"+receiveText);
dispatch(client, receiveText);
client = (SocketChannel) selectionKey.channel();
client.register(selector, SelectionKey.OP_READ);
}
}
}
/**
* 把当前客户端信息 推送到其他客户端
*/
private void dispatch(SocketChannel client,String info) throws IOException{
Socket s = client.socket();
String name = "["+s.getInetAddress().toString().substring(1)+":"+Integer.toHexString(client.hashCode())+"]";
if(!clientsMap.isEmpty()){
for(Map.Entry entry : clientsMap.entrySet()){
SocketChannel temp = entry.getValue();
if(!client.equals(temp)){
sBuffer.clear();
sBuffer.put((name+":"+info).getBytes());
sBuffer.flip();
//输出到通道
temp.write(sBuffer);
}
}
}
clientsMap.put(name, client);
}
public static void main(String[] args) throws IOException {
NIOSServer server = new NIOSServer(7777);
server.listen();
}
}
客户端,可运行启动多个:
Java代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Set;
public class NIOClient {
/*发送数据缓冲区*/
private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);
/*接受数据缓冲区*/
private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);
/*服务器端地址*/
private InetSocketAddress SERVER;
private static Selector selector;
private static SocketChannel client;
private static String receiveText;
private static String sendText;
private static int count=0;
public NIOClient(int port){
SERVER = new InetSocketAddress("localhost", port);
init();
}
public void init(){
try {
/*
* 客户端向服务器端发起建立连接请求
*/
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT);
socketChannel.connect(SERVER);
/*
* 轮询监听客户端上注册事件的发生
*/
while (true) {
selector.select();
Set keySet = selector.selectedKeys();
for(final SelectionKey key : keySet){
handle(key);
};
keySet.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
NIOClient client = new NIOClient(7777);
}
private void handle(SelectionKey selectionKey) throws IOException{
if (selectionKey.isConnectable()) {
/*
* 连接建立事件,已成功连接至服务器
*/
client = (SocketChannel) selectionKey.channel();
if (client.isConnectionPending()) {
cli