http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/



Following up on my previous post, we also had to demonstrate a sample Java TCP Server and TCP Client. The code footprint pretty small and it gives you a good idea about how a TDP Server opens up a port, and then the TCP Client sends or receives data from that port.

This is a good page on the differences between TCP and UDP.

To compile these, install Java JDK to your system. Then compile the program with javac TCPClient.java – this will create a TCPClient.class. Execute the file with java TCPClient – leave off the .class, or you will get the error: “Exception in thread “main” java.lang.NoClassDefFoundError”.

Here is sample code for a simple Java TCP Server/Client, originally from the excellent Computer Networking: A Top Down Approach, by Kurose and Ross:

TCPServer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;
import java.net.*;

class TCPServer
{
   public static void main(String argv[]) throws Exception
      {
         String clientSentence;
         String capitalizedSentence;
         ServerSocket welcomeSocket = new ServerSocket(6789);

         while(true)
         {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient =
               new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println("Received: " + clientSentence);
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);
         }
      }
}

and the client:

TCPClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.*;
import java.net.*;

class TCPClient
{
 public static void main(String argv[]) throws Exception
 {
  String sentence;
  String modifiedSentence;
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost"6789);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  sentence = inFromUser.readLine();
  outToServer.writeBytes(sentence + '\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("FROM SERVER: " + modifiedSentence);
  clientSocket.close();
 }
}

If you have any questions, please leave a comment!