Skip to content

Creating a Client

Ben edited this page Oct 24, 2022 · 5 revisions

This time we will look at how to create a client.

The code:

package dev.bitbite.networking.example;

import dev.bitbite.networking.Client;

public class ExampleClient extends Client {

	public ExampleClient(String host, int port) {
		super(host, port);
	}

	@Override
	protected void processReceivedData(byte[] raw) {
		String data = new String(raw);
		System.out.println(data);
	}

	public static void main(String[] args){
		ExampleClient client = new ExampleClient("localhost", 1337);
		client.connect();
	}

}

Same as the Server-side. Pretty easy right? Again, when instantiated the client will connect to the specified host and port. Whenever data from the server is received it is passed through some optional preprocessing steps (more on that in the data-preprocessing layers chapter) and finally forwarded to processReceivedData(byte[]) with the byte[] being the data from the server. Here it just gets output to console.

To start the client instantiate it using ExampleClient client = new ExampleClient("localhost", 1337); and start the connection process using client.connect();. Now it will try to connect to the server on your localhost on port 1337. If you followed the guide on How to create a Server and started it the client will connect to that server. If you would send data to the client using client.send(byte[]); this data would be sent to the server which will output it to console and send it back to the client which will output it aswell. the client will keep running until you either get disconnected (may it be on purpose or on connection loss) or you close the connection manually by calling client.close();

The client automatically detects when the server disconnects. This is done using a separate thread to ensure server disconnection is being detected asap.

Creating a Client involves some steps under the hood, which will be covered in the following chapters. Next up learn how to listen for certain events using [ClientListeners] and [IOHandlerListeners]

So far, so easy, right?

Clone this wiki locally