服务端代码实现
package chat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
public class ChatServer {
private ServerSocketChannel serverSocketChannel;
private Selector selector;
private static final int PORT = 9999;
public ChatServer(){
try {
serverSocketChannel = ServerSocketChannel.open();
selector = Selector.open();
serverSocketChannel.bind(new InetSocketAddress(PORT));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
printInfo("Chat Server is ready......");
} catch (IOException e) {
e.printStackTrace();
}
}
public void start(){
try {
while (true) {
if(selector.select(2000) == 0){
System.out.println("Server:没有客户端找我,我就干别的事");
continue;
}
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ);
System.out.println(socketChannel.getRemoteAddress().toString().substring(1) + "上线了...");
}
if (selectionKey.isReadable()) {
readMsg(selectionKey);
}
keyIterator.remove();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void printInfo(String msg) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("[" + dateFormat.format(new Date()) + "] ->" + msg);
}
private void readMsg(SelectionKey selectionKey) throws Exception{
SocketChannel channel = (SocketChannel)selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int count = channel.read(byteBuffer);
if (count > 0) {
String msg = new String(byteBuffer.array());
printInfo(msg);
broadCast(channel,msg);
}
}
private void broadCast(SocketChannel except, String msg) throws Exception{
System.out.println("服务器发送了广播...");
for (SelectionKey key: selector.keys()) {
Channel targetChannel = key.channel();
if (targetChannel instanceof SocketChannel && targetChannel != except) {
SocketChannel destChannel = (SocketChannel)key.channel();
ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
destChannel.write(byteBuffer);
}
}
}
public static void main(String[] args) {
ChatServer server = new ChatServer();
server.start();
}
}
客户端代码实现
package chat;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class ChatClient {
private final String HOST = "127.0.0.1";
private int PORT = 9999;
private SocketChannel socketChannel;
private String userName;
public ChatClient() throws Exception{
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
InetSocketAddress socketAddress = new InetSocketAddress(HOST, PORT);
if (!socketChannel.connect(socketAddress)) {
while (!socketChannel.finishConnect()) {
System.out.println("Client:连接服务器的同时,我还可以干别的事情");
}
}
userName = socketChannel.getLocalAddress().toString().substring(1);
System.out.println("----------------------Client(" + userName + ") is ready-----------------------");
}
public void sendMsg(String msg) throws Exception{
if (msg.equalsIgnoreCase("bye")) {
socketChannel.close();
return;
}
msg = userName + "说: " + msg;
ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
socketChannel.write(byteBuffer);
}
public void receiveMsg() throws Exception{
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int count = socketChannel.read(byteBuffer);
if (count > 0) {
String msg = new String(byteBuffer.array());
System.out.println(msg.trim());
}
}
}
启动客户端
package chat;
import java.util.Scanner;
public class TestClient {
public static void main(String[] args) throws Exception{
ChatClient client = new ChatClient();
new Thread() {
public void run(){
try {
while (true) {
client.receiveMsg();
Thread.sleep(2000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String msg = scanner.nextLine();
client.sendMsg(msg);
}
}
}