Tips & Tricks for Technologists & System Administrators | About & Contact

A Simple Java TCP Server and TCP Client


Posted 18th September in Code Samples, Java, Software. 43 Comments

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!


Originally posted 20080918 and last touched 20110422
Dave Drager+ is the Chief Technology Officer at XDA-Developers, where he keeps the server farm running efficiently for millions of visitors per day. He has written previously for the technology blogs Lifehacker and MakeUseOf.


  • Pingback: Dave Drager

  • 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

  • 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

  • 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.

  • 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.

  • Floatrolo

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

  • Floatrolo

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

  • Venessa

    you forgot

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

    anyway, thanks, exactly what I needed :)

  • Venessa

    you forgot

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

    anyway, thanks, exactly what I needed :)

  • 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

  • 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

  • http://davedrager.com Dave Drager

    @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.

  • http://systembash.com Dave

    @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.

  • tam

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

  • tam

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

  • grüner tee

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

  • grüner tee

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

  • 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

  • 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

  • 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

  • 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

  • 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.

  • 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.

  • Pingback: Dave Drager

  • arthika

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

  • arthika

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

  • http://system.com arthika

    Hi…
    i need chatting program in java
    pls help me

  • http://system.com arthika

    Hi…
    i need chatting program in java
    pls help me

  • http://mystikrpg.com weka

    I run server than client… nothing happens…………

  • Dan

    I run server than client… nothing happens…………

  • Deepusxn63

    what is the output for dis program plz?

  • http://www.facebook.com/people/Kenoye-Rukari/538001588 Kenoye Rukari

    hi, how can i write an object to the client and vise versa?

  • Annieta J

    chat program in java please?

  • http://www.facebook.com/people/Sirbi-Kotrappa/1817995855 Sirbi Kotrappa

    please some body suggest me, how to develop simple simulated Java client-server for File Exchange

  • http://pulse.yahoo.com/_4QXWSYX5XSMU2DPDJKF4DA2IQM Zohaib

    i am using this code but this code released error (connection reset)

  • Bhanusankar Bsc

    what is the exact output for this program…

  • aredline

    Best simple code!

    @Bhanusankar Bsc
    The input string in uppercase:
    System.out.println(“Received: ” + clientSentence);
    capitalizedSentence = clientSentence.toUpperCase() + ‘n';
    outToClient.writeBytes(capitalizedSentence);//response to the client

  • Rad

    hi, if you run the client, then type something like “hello world” and then press enter, the server and the client will respond (only obvious if you read the code)

  • Rad

    the out put is whatever you type into the client via this line in the code:

    sentence = inFromUser.readLine();
    outToServer.writeBytes(sentence + ‘n’);

  • Koueik Anthony

    hi i am new in Java and android…my app is not working , i can connect and send data to the server( PC .net server)

    the server send me ” 3 string”

    through your code … i wrote this solution but it is not working :

    while(true){

    try {

    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));

    message = inFromServer.readLine();

    Toast.makeText(client.this, message,Toast.LENGTH_LONG).show();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    Toast.makeText(client.this, “not working”,Toast.LENGTH_LONG).show();

    e.printStackTrace();

    }

    }

    can you tell me what’s wrong… Please

  • Noor Nust

     in this code there are two classes in which it has two main. so how i write this code…

  • Lefteris

    try moving the while loop just before the message = infromserver.readline().

    your current code creates thousands of inputStreanReaders and bufferReaders.
    also make sure when sending you end your strings with n since you are using the readline method.
    if it still isn’t fixed try after sending calling the .flush() mehod on the dataoutputstream (if such method exists not sure)

  • Wander

    Yep. But why do u use main function twice and there are no Threads?