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 Computer Networking: A Top Down Approach, by Kurose and Ross:

TCPServer.java

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

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!

Share and Enjoy:
  • Twitter
  • del.icio.us
  • Digg
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Print
  • StumbleUpon

2 Trackbacks

You can leave a trackback using this URL: http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/trackback/

  1. By Dave Drager on September 18, 2008 at 1:01 pm

    New blog post: A Simple Java TCP Server and TCP Client http://tinyurl.com/3vt9x9

  2. By Dave Drager on March 29, 2010 at 2:11 pm

    New Post: A Simple Java TCP Server and TCP Client http://bit.ly/5L5Kbt

13 Comments

  1. Michel

    Hi

    simply what I needed :)

    Is it possible to add persistence to this example (inserting the data into a Firebird db, the data is in binary format)?

    Best regards,
    Michel

    Posted October 15, 2008 at 12:17 pm | Permalink
  2. The Professor

    I wrote my first Java socket client/server application in 1993! So this code looks mighty familiar.

    However, servers I’ve written subsequently all implement Thread so you can build a pool of connections available and new ones are spawned as traffic arrives. A small point, but one that makes this code scalable.

    Posted October 21, 2008 at 2:14 pm | Permalink
  3. Floatrolo

    Hi, Congratulations to the site owner for this marvelous work you’ve done. It has lots of useful and interesting data.

    Posted June 4, 2009 at 6:58 pm | Permalink
  4. Venessa

    you forgot

    import java.net.Socket;
    and
    public static void main(String[] args) throws IOException {

    anyway, thanks, exactly what I needed :)

    Posted June 9, 2009 at 8:22 am | Permalink
  5. vince

    Hi, there are nice work for a simple and easy understand server client example.
    However, I have some question which is:
    what is the use of ‘\n’ in
    outToServer.writeBytes(sentence + ‘\n’);

    i try to remove it and the program won’t work. Can you please do simple explain to me?
    Thanks

    Vince

    Posted July 20, 2009 at 4:44 am | Permalink
  6. @vince: \n stands for new line. This lets the TCP Server know that your sentence has been sent. Let me know if you have any other questions.

    Posted July 20, 2009 at 6:32 am | Permalink
  7. tam

    i need java code that display the area of a circle using TCP server and TCPclient

    Posted September 10, 2009 at 9:05 am | Permalink
  8. grüner tee

    The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications.

    Posted December 5, 2009 at 2:44 pm | Permalink
  9. sara

    HI,,,,
    I have cpyied the TCPClient code on my pc
    and the TCPServer code on another pc but nothing happened
    “there is no error”.
    please reply

    Posted January 10, 2010 at 2:20 pm | Permalink
  10. AbdelAziz

    Thanks man…
    it really helps… :)
    but I would like to modify this code so that the client sends a request to the server to “add 10 20″ then the server will calculate it and send back 30 :) I will try to do.. thanks dude

    Posted March 20, 2010 at 4:26 pm | Permalink
  11. Mike

    I’m trying to figure out how to add a login mechanism to this code. I also want the server to be the one that grants access not the client for obvious reasons. I’m sending the user/pass through the same socket that will be used for communication, yet my program crashes right at the point of asking for the password. User name gets through no problem. I believe it is some kind of connection reset error.

    Posted March 28, 2010 at 9:34 am | Permalink
  12. arthika

    Hi…
    I want chatting program in java as client side and server side
    pls help me

    Posted July 6, 2010 at 4:50 am | Permalink
  13. Hi…
    i need chatting program in java
    pls help me

    Posted July 6, 2010 at 4:53 am | Permalink

Post a Comment

Your email is never shared. Required fields are marked *

*
*