Network Programming in Java - #3 - Creating a Test Client

Introduction: This tutorial is the third in my Java Network Programming using KryoNet series in which we are creating a test client to connect to our test server. Previous: In the previous tutorial we created a test server. IMPORTANT: A) Your server and client can not be running at the same time, in Eclipse, in the same Java Project. Follow my first tutorial to create a second Java Project within Eclipse and use one for the client and the other for the server. B) Make sure you do not name your class something that will obstruct the KryoNet classes (such as Client). Test Client: So first, create a new file called ClientCustom (can be whatever you like) and add the following imports...
  1. import java.io.IOException;
  2. import com.esotericsoftware.kryonet.Client;
Next we are going to create the basic Java Application main method to create a new instance of the current class once the application is ran...
  1. public class ClientCustom {
  2. public static void main(String args[]) {
  3. new ClientCustom();
  4. }
  5. }
Now we need the constructor. This is where we will create the client. First we create a new Client object named "client"...
  1. public ClientCustom() {
  2. Client client = new Client();
  3. }
Once it is created, we start the client...
  1. public ClientCustom() {
  2. Client client = new Client();
  3. client.start();
  4. }
Then finally we connect to the server using the connect method. The first argument is the timeout for the connection, second is the IP of the server (the host machine, both my client and server are on my network so I just put my localhost...), third and fourth are the TCP and UDP ports (these must be the same as on the server)...
  1. public ClientCustom() {
  2. Client client = new Client();
  3. client.start();
  4. try {
  5. client.connect(5000, "127.0.0.1", 54555, 54777);
  6. } catch (IOException e) {
  7. System.out.println("Server is not started. Can not connect.");
  8. }
  9. }
We surround it with try and catch in case the connection fails, we output "Server is not started. Can not connect." to the console. Testing: Now try to run the server, you should receive the following message in the console... 00:00 INFO: [kryonet] Server opened. Then run the client, you should receive the following message in the console... 00:00 INFO: Connecting: /127.0.0.1:54555/54777 00:00 INFO: [kryonet] Connection 1 connected: /127.0.0.1 While at the same time, you should receive this in the server console... 00:00 INFO: [kryonet] Server opened. 00:02 INFO: [kryonet] Connection 1 connected: /127.0.0.1 00:03 INFO: [kryonet] Connection 1 disconnected. Note; the connection auto-disconnects because there is no loop in the client to keep it open and maintain the connection, there will be once we create a proper client.

Add new comment