Network Programming in Java - #2 - Creating a Test Server

Submitted by: 
Language: 
Visitors have accessed this post 124 times.

Introduction:
This tutorial is the second in my Java Network Programming using KryoNet series in which we are creating a test server.

Previous:
In the previous tutorial we downloaded the KryoNet files and set up our projects.

Test Server:
So first, create a new file called Main (can be whatever you like) and add the following imports...

  1. import java.io.IOException;
  2. import com.esotericsoftware.kryonet.Server;

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 Main {
  2. public static void main(String args[]) {
  3. new Main();
  4. }
  5. }

Now we need the constructor. This is where we will create the test server. First we create a new Server object named "server"...

  1. public Main() {
  2. Server server = new Server();
  3. }

Once it is created, we start the server...

  1. public Main() {
  2. Server server = new Server();
  3. server.start();
  4. }

Then finally we bind it to the ports. The first argument input is the TCP port, while the second is the UDP port. The recommended ports for KryoNet are as follows...

  1. public Main() {
  2. Server server = new Server();
  3. server.start();
  4. try {
  5. server.bind(54555, 54777);
  6. } catch (IOException e) {
  7. e.printStackTrace();
  8. }
  9. }

We surround it with try and catch statements for two reasons;
1 - It's required by Java in case of an IOException.
2 - We can create custom handles to deal with the binding problem.

Testing:
Now try to run the program, you should receive the following message in the console...

00:00 INFO: [kryonet] Server opened.


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.