Network Programming in Java - #4 - Receiving and Sending Data - Server Listener & Client sendTCP Method

Introduction: This tutorial is the fourth in my Java Network Programming using KryoNet series in which we are going to be adding a listener to our server and sending test data over TCP from the client to the server. Previous: In the previous tutorial we created a test client to connect to our test server. TCP vs. UDP: TCP and UDP are both Protocols which transmit data from one point to another through data streams. TCP guarantees the data will get to its destination and the program will await for this even before continuing with it's scripts, while UDP is not Asynchronous and the script will simply begin* to send the data and continue with the rest of the script. Client Sending TCP Data: Before we create a listener on our server, we are going to setup a simple one line of code in our client to send data to the server. We use the .sendTCP method to send TCP data, or .sendUDP to send UDP data to the server the client object being references is connected to...
  1. client.sendTCP("Data");
-We put this code just under our try and catch statement to connect to the server, for now at least- Server Listener: Now that our client will send data to the server, we want to accept the data by adding a listener to our server. A listener is something which awaits for an event to occur before executing script - in our case, it is waiting for incoming data to be sent to the local server before it executes what to do with the data received.
  1. server.addListener(new Listener() {
  2. public void received(Connection connection, Object object) {
  3. System.out.println("Incoming connection of data...");
  4. }
  5. });
-Again, we put this just under our try and catch statement to bind the server to the TCP and UDP ports, for now at least- So, the above listener waits for data to be received, then once data is received, it simply outputs the message "Incoming connection of data..." to the console, we don't use the data received (the object) yet, but we will in the next or near future tutorials.

Add new comment