Network Programming in Java - #3 - Creating a Test Client
Submitted by GeePee on Wednesday, April 29, 2015 - 22:20.
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...
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...
Now we need the constructor. This is where we will create the client. First we create a new Client object named "client"...
Once it is created, we start the client...
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)...
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.
- import java.io.IOException;
- import com.esotericsoftware.kryonet.Client;
- public class ClientCustom {
- new ClientCustom();
- }
- }
- public ClientCustom() {
- Client client = new Client();
- }
- public ClientCustom() {
- Client client = new Client();
- client.start();
- }
- public ClientCustom() {
- Client client = new Client();
- client.start();
- try {
- client.connect(5000, "127.0.0.1", 54555, 54777);
- }
- }
Add new comment
- 40 views