How it fits together
The launcher, the server core, threads
The launcher
com.Main creates a Launcher and calls startThreads(). That is all it does:
public static void main(String[] args) {
launcher = new Launcher(args.length > 0 ? args[0] : Launcher.DEFAULT_CONFIG);
launcher.startThreads();
}
The launcher reads the config in three stages, each its own class in com.lang.conf:
- ConfLexer turns the text into tokens: words, block headers, line breaks. Comments and quotes are handled here.
- ConfParser turns tokens into a flat program of four instructions:
AppDef(the name),Def(a block opens),Func(a setting) andFed(the block closes). - ConfInterpreter fills in environment variables.
The launcher then executes the program. Each time a block closes it builds what the block describes and adds it to a list of threads.
Start order
Threads start one at a time, in file order. Each thread calls Main.launcher.nextStage() when it is ready:
the database manager once it has connected, a server once its port is open, the login handler once its tables
exist and its sessions are loaded. Only then does the next thread start. So a web server never takes a request
before the database it needs is there.
[Database] Connected to shop at localhost:3306 as shop_user [Login] Ready. 3 live sessions, 0 bans. [HTTP] Listening on 0.0.0.0:8080 [Launcher] Started 4 threads: DatabaseManager, LoginHandler, HTTP:8080, Console
If a thread fails to get ready (a port in use, a database that is down) it says so and the launcher carries on, so one failure does not hide the rest. A thread that never reports is skipped after 15 seconds.
The server core
Every server in JBend, whatever it speaks, is the same class: com.server.Server, one thread around one
java.nio selector, handling every connection on its port without a thread per client. What differs is the
Protocol plugged into it.
bytes in messages socket ---> Server ---> Protocol.receive() ---> your code socket <--- Server <--- connection's send queue <--- c.sendMessage()
- Reading. TCP delivers a stream, not messages: a read may hold half a request or three of them. The server hands whatever arrived to the protocol, which keeps unfinished data in the connection's inbound buffer until a whole message is there.
- Writing. Sends never block. Bytes are queued on the connection and written as the socket accepts them, so a large file or a slow client cannot stall anyone else, and nothing is cut short. A client that stops reading is dropped once 32 MB is waiting for it.
- Closing.
c.disconnect()closes after everything queued has been written.c.kill()closes now. - Thread safety. Sending to and disconnecting a connection are safe from any thread, which matters because database callbacks and game loops do both.
- Flood protection. An address that opens more than 120 connections in 10 seconds is refused for 5 minutes. Local connections are exempt, since behind a proxy everyone arrives from 127.0.0.1.
Connections
A ServerConnection is one client. The methods you will use:
| Method | Does |
|---|---|
sendMessage(String) | Send in the protocol's format: a WebSocket frame, a line of TCP. |
sendBytes(byte[]) | Send raw bytes. |
disconnect() / kill() | Close after pending writes / close immediately. |
set(key, value) / get(key) | Attach your own state to the connection: a player, a room, a counter. |
getUser() | The logged-in account, or null. |
getClientIP() | The visitor's address, read from X-Forwarded-For when the connection came through a local proxy. |
getConnectionID() | A small number unique among this server's open connections. |
isClosed() | True once dropped. Sends to a closed connection are ignored. |
Your own thread
An app block starts any Runnable. For a loop that ticks, extend NetApplication:
package com.example;
import com.Main;
import com.NetApplication;
import com.console.Console;
public class Heartbeat extends NetApplication {
public String getAppName() { return "Heartbeat"; }
public int tickMillis() { return 5000; }
public void runApplication() {
Console.output("Heartbeat", Main.launcher.totalConnections() + " connections");
}
}
app: class com.example.Heartbeat
Your code reaches everything else through Main.launcher:
| Call | Returns |
|---|---|
databaseManager() | The database manager, or null without a dataserver block. |
getLoginHandler() | The login handler, or null without a login block. |
getServer(port), servers() | A server by port; all servers. |
getWebServer(), getWebsocketServer(), getServer() | The first HTTP, WebSocket or TCP server. |
setting(name, fallback) | A value from a set line. |
putStatus(key, supplier) | Adds a value of yours to /api/status. |
getApplicationName(), appVersion(), uptimeString() | What they say. |
Which thread runs my code?
| Code | Runs on |
|---|---|
A protocol's hooks (handle, processCustomMessage, processMessage, onClose) | That server's thread. Keep them quick: while one runs, that port handles nothing else. |
ServerQuery.done(), login callbacks | The database thread. |
An app class | Its own thread. |
| Console commands | The console thread. |
State touched from more than one of these needs a lock. JBGame guards its whole world with one
(synchronized (game.lock)), which is the simplest thing that works.
Assembling in code instead
The config file is the intended way, but the same pieces can be put together by hand, which is how JBend 1.x applications were written and still works:
Launcher launcher = new Launcher(); // empty: reads no file
Main.launcher = launcher;
launcher.addDatabaseManager("localhost", "shop", "shop_user", "s3cret");
launcher.addLoginHandler();
launcher.addServer(new Site("res/front/", 8080));
launcher.addServer(new Chat(8081));
launcher.loadThread(new Heartbeat(), "Heartbeat");
launcher.addConsole();
launcher.startThreads();