package com.test.example.chat;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
public class ChatServer {
public static void main(String[] args) {
// 客户端列表
Hashtable<String, SocketChannel> clientlist = new Hashtable<String, SocketChannel>();
Selector selector = null;
ServerSocketChannel server = null;
try {
// 创建一个Selector
selector = Selector.open();
// 创建Socket并注册
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
// 启动端口监听
InetSocketAddress ip = new InetSocketAddress(12345);
server.socket().bind(ip) ;
// 监听事件
while (true) {
// 监听事件
selector.select();
// 事件来源列表
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
// 删除当前事件
it.remove();
// 判断事件类型
if (key.isAcceptable()) {
// 连接事件
ServerSocketChannel server2 = (ServerSocketChannel) key
.channel();
SocketChannel channel = server2.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
System.out.println("客户端连接:"
+ channel.socket().getInetAddress()
.getHostName() + ":"
+ channel.socket().getPort());
} else if (key.isReadable()) {
// 读取数据事件
SocketChannel channel = (SocketChannel) key.channel();
// 读取数据
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
ByteBuffer buffer = ByteBuffer.allocate(50);
channel.read(buffer);
buffer.flip();
String msg = decoder.decode(buffer).toString();
System.out.println("收到:" + msg);
if (msg.startsWith("username=")) {
String username = msg.replaceAll("username=", "");
clientlist.put(username, channel);
} else {
// 转发消息给客户端
String[] arr = msg.split(":");
if (arr.length == 3) {
String from = arr[0];//发送者
String to = arr[1];//接收者
String content = arr[2];//发送内容
if (clientlist.containsKey(to)) {
CharsetEncoder encoder = Charset.forName(
"UTF-8").newEncoder();
// 给接收者发送消息
clientlist.get(to).write(
encoder.encode(CharBuffer.wrap(from
+ ":" + content)));
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭
try {
selector.close();
server.close();
} catch (IOException e) {
}
}
}
}
package com.test.example.chat;
import java.io.*;
public class ChatClient {
public static void main(String[] args) {
String username = args[0];
ClientThread client = new ClientThread(username);
client.start();
// 输入输出流
BufferedReader sin = new BufferedReader(
new InputStreamReader(System.in));
try {
// 循环读取键盘输入
String readline;
while ((readline = sin.readLine()) != null) {
if (readline.equals("bye")) {
client.close();
System.exit(0);
}
client.send(username + ":" + readline);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.test.example.chat;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
public class ClientThread extends Thread {
private CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
private CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
private Selector selector = null;
private SocketChannel socket = null;
private SelectionKey clientKey = null;
private String username;
// 启动客户端
public ClientThread(String username) {
try {
// 创建一个Selector
selector = Selector.open();
// 创建Socket并注册
socket = SocketChannel.open();
socket.configureBlocking(false);
clientKey = socket.register(selector, SelectionKey.OP_CONNECT);
// 连接到远程地址
InetSocketAddress ip = new InetSocketAddress("localhost", 12345);
socket.connect(ip);
this.username = username;
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取事件
public void run() {
try {
// 监听事件
while (true) {
// 监听事件
selector.select();
// 事件来源列表
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
// 删除当前事件
it.remove();
// 判断事件类型
if (key.isConnectable()) {
// 连接事件
SocketChannel channel = (SocketChannel) key.channel();
if (channel.isConnectionPending())
channel.finishConnect();
channel.register(selector, SelectionKey.OP_READ);
System.out.println("连接服务器端成功!");
// 发送用户名
send("username=" + this.username);
} else if (key.isReadable()) {
// 读取数据事件
SocketChannel channel = (SocketChannel) key.channel();
// 读取数据
ByteBuffer buffer = ByteBuffer.allocate(50);
channel.read(buffer);
buffer.flip();
String msg = decoder.decode(buffer).toString();
System.out.println("收到:" + msg);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭
try {
selector.close();
socket.close();
} catch (IOException e) {
}
}
}
// 发送消息
public void send(String msg) {
try {
SocketChannel client = (SocketChannel) clientKey.channel();
client.write(encoder.encode(CharBuffer.wrap(msg)));
} catch (Exception e) {
e.printStackTrace();
}
}
// 关闭客户端
public void close() {
try {
selector.close();
socket.close();
} catch (IOException e) {
}
}
}
NIO消息发送(Client/Server)
最新推荐文章于 2022-05-21 09:29:20 发布