Light-fast java chat server
We are going to use java to write server where multiple TCPclients will connect to our server over telnet or any such client and our server will handle connections using NIO package specifically with Channels and Selectors.
package com.magticom;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;
import static java.lang.IO.println;
/**
* @author Konstantine Vashalomidze
*/
public class ChatServer {
static void main() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
try (var selector = Selector.open(); var serverSock = ServerSocketChannel.open()) {
serverSock.configureBlocking(false);
serverSock.bind(new InetSocketAddress("localhost", 6969));
serverSock.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
var keys = selector.selectedKeys();
var iterator = keys.iterator();
while (iterator.hasNext()) {
var key = iterator.next();
if (key.isAcceptable()) {
var clientSockCh = serverSock.accept();
clientSockCh.configureBlocking(false);
clientSockCh.register(selector, SelectionKey.OP_READ);
println("New connection accepted: " + clientSockCh.getRemoteAddress());
} else if (key.isReadable()) {
var clientSockCh = (SocketChannel) key.channel();
buffer.clear();
while (clientSockCh.read(buffer) > 0) {
Set allKeys = selector.keys();
for (var otherClientSockChKey : allKeys) {
if (otherClientSockChKey.channel() instanceof SocketChannel ch) {
if (ch != clientSockCh) {
buffer.flip();
ch.write(buffer);
buffer.clear();
}
}
}
}
}
keys.remove(key);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
To see how this works follow these instructions:
-
Withing the directory where our ChatServer.java file lies we should execute this command so that java automatically compiles and executes our program:
java ChatServer.java -
Then we open two separate terminals (Assuming telnet it has telnet installed or any other similar client) and execute in both of them:
telnet localhost 6969
What happened now is that both of the telnet clients are connected to our server, and they can both exchange the messages with each other, feel free to type in anything. Note also that there is no disconnection logic implemented in this version to keep the code clean.