Skip to content

Server and Client Setup

mega12345mega edited this page Jan 26, 2023 · 1 revision

Server

When creating a Server, you must supply the port. You can then add other attributes, including listeners and enabling web socket mode. Whenever a client connects to a server, the server gets a new ServerConnection. This allows you to send and receive packets from that specific client.

Example:

Server server = new Server(31415) // Start on port 31415
        .useWebSocket(true) // Enable web socket mode
        .setSecure(ssl) // Use wss://
        .addConnectionListener((conn, wait) -> {}) // When a client connects
        .addPacketListener((packet, conn, wait) -> {}) // When a packet is received
        .setConnectAllowed(false) // Disable connections, enabled by default
        .start(); // Start the server

server.registerPacket(ChatMessagePacket.class); // Allow sending and receiving ChatMessagePacket
server.setConnectAllowed(true); // Re-enable new connections

server.sendPacket(new ChatMessagePacket("Hello server!")); // Sends ChatMessagePacket to all clients
server.sendPacket(new ChatMessagePacket("Shhhh"), server.getConnections().stream().findFirst().get()); // Don't broadcast to the first connection

// The server is reusable
server.close();
server.start();

Client

When creating a Client, you must supply the port, and optionally the IP. The IP defaults to localhost. Both ServerConnection and Client extend Connection, so you can also send and receive packets directly from the Client object.

Example:

Client client = new Client("wss://192.168.0.27", 31415)
        .useWebSocket(true) // Enable web socket mode
        .setConnectTimeout(60000) // Attempt to connect for a full minute (default 5s)
        .addPacketListener((packet, conn, wait) -> {}); // When a packet is received (conn == client)
client.registerPacket(ChatMessagePacket.class); // Usually you should register your packets before starting
client.start(); // Connect to the server, blocking until success or timeout

client.sendPacket(new ChatMessagePacket("Hi, I'm the new client!"));

// The client is also reusable
client.close();
client.start();

Clone this wiki locally