TCP, bridge and proxy

com.server.protocol.TCP, Protocol, WebSocketBridge, TCPProxy

Line-based TCP

The tcp block starts a plain TCP server. Each line a client sends is one message; each message the server sends has a newline added. Without a handler it echoes, which is useful for checking a port:

tcp:
listen 9000
$ nc localhost 9000
hello
hello

Give it behaviour by extending TCP:

public class Chat extends TCP {
    public Chat(int port) { super(port); }

    @Override
    public void processMessage(ServerConnection c, String line) {
        if (line.equals("quit")) { c.sendMessage("bye"); c.disconnect(); return; }
        getServer().broadcast(c.getConnectionID() + ": " + line);
    }
}
tcp:
listen 9000
handler com.example.Chat
greeting "let me in"

greeting makes every client send that exact line first. It is not security, but it turns away port scanners and stray HTTP requests cheaply. Lines longer than 64 KB close the connection.

Your own protocol

For anything that is not lines (a binary format, or packets with their own delimiters) extend Protocol and implement receive. The rule to remember is that TCP is a stream: one receive call may bring part of a packet, exactly one, or several. Collect bytes in the connection's inbound buffer and take whole packets from the front.

/** Packets are a 2-byte length followed by that many bytes. */
public class Framed extends Protocol {

    public Framed(int port) { super("Framed", Protocol.TCP, port); }

    @Override
    public void receive(ServerConnection c, byte[] data) {
        c.inbound().write(data, 0, data.length);
        byte[] all = c.inbound().toByteArray();
        int pos = 0;
        while (all.length - pos >= 2) {
            int len = ((all[pos] & 0xFF) << 8) | (all[pos + 1] & 0xFF);
            if (all.length - pos - 2 < len)
                break;                                   // the rest hasn't arrived yet
            byte[] packet = java.util.Arrays.copyOfRange(all, pos + 2, pos + 2 + len);
            pos += 2 + len;
            handle(c, packet);
        }
        consume(c, all, pos);                            // keep what is left for next time
    }

    private void handle(ServerConnection c, byte[] packet) { /* ... */ }

    @Override
    public void processMessage(ServerConnection c, String data) { }
}

Other hooks every protocol has: onConnect(c), onDisconnect(c), onTick(c, now) (about once a second per connection, for timeouts) and onServerStart().

The WebSocket bridge

Browsers cannot open TCP sockets. A bridge block is a WebSocket server that opens a TCP connection to another server for each browser that connects, and relays bytes both ways. The TCP server needs no changes.

bridge:
listen 8092
bind 127.0.0.1
target 127.0.0.1 10018

This is how the live demo puts a 2018 Java game server, which only speaks TCP, in a browser. The page's script does the same packet framing the desktop client does, because the bridge passes the stream through untouched: a message from the TCP side may arrive split in two or joined to the next.

Data from the TCP side reaches the browser as binary messages (an ArrayBuffer); mode text sends text messages instead, for protocols that are plain ASCII.

The proxy

A proxy block listens on one port and forwards each connection to a local backend chosen by the Host header, so several applications can share port 80:

proxy:
listen 80
map example.com 8080
map game.example.com 8081
default 8080

It reads the first request's headers to find the host and then relays bytes in both directions untouched, so WebSocket upgrades pass through. It does not terminate TLS and does not add forwarding headers; for a public site a dedicated reverse proxy in front is the better tool. Ports below 1024 need root or setcap on Linux.