TCP Server and TCP Client in Java

By: Ashish Myles  

The Socket class is in the java.net package, so be sure to say import java.net.*; at the beginning of your file. The following is a simple example that illustrates the different portions of a server/client pair. This example works using localhost, which corresponds to the default local computer IP address of 127.0.0.1. This way, both the server and the client will be running on the same computer. Server.java and Client.java contain the server and client source code for this simple example.

Here is the server code (Server.java):

import java.lang.*;
import java.io.*;
import java.net.*;

class Server {
   public static void main(String args[]) {
      String data = "Toobie ornaught toobie";
      try {
         ServerSocket srvr = new ServerSocket(1234);
         Socket skt = srvr.accept();
         System.out.print("Server has connected!\n");
         PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
         System.out.print("Sending string: '" + data + "'\n");
         out.print(data);
         out.close();
         skt.close();
         srvr.close();
      }
      catch(Exception e) {
         System.out.print("Whoops! It didn't work!\n");
      }
   }
}

The key portions of this program are in the try{} block. The ServerSocket instantiation is what sets up the server to listen at the given port. The server is automatically set up at the computer on which it is run. The Socket instantiation on the next line uses the accept() method of ServerSocket. This method waits until a client attempts to connect to the server, and it returns an instance of the Socket class. This Socket instance (skt) is now the "warp tunnel" through which we can communicate with the client. skt.getOutputStream() returns the output stream through which the server can talk to the client, and skt.getInputStream() returns the input stream through with the server can hear the client. This example creates a PrintWriter instance using the output stream for easier output and sends the data (stored in data) to the client (out.print(data);). Bingo! Easy as that! After everything is done, all the streams and sockets shuold be closed before the program is exited. Now, let's see the client code.

Here is the client code (Client.java):

import java.lang.*;
import java.io.*;
import java.net.*;

class Client {
   public static void main(String args[]) {
      try {
         Socket skt = new Socket("localhost", 1234);
         BufferedReader in = new BufferedReader(new
            InputStreamReader(skt.getInputStream()));
         System.out.print("Received string: '");

         while (!in.ready()) {}
         System.out.println(in.readLine()); // Read one line and output it

         System.out.print("'\n");
         in.close();
      }
      catch(Exception e) {
         System.out.print("Whoops! It didn't work!\n");
      }
   }
}

Once again, the meat of the program is in the try{} block. A connection to the server is attempted through the instantiation of the Socket class. It attempts to contact the server at localhost through port 1234 - the same port where the server is listening. Once the socket is at hand, it works exactly the same as the one obtained through the ServerSocket class in Server.java. This time, the input stream is obtained and a BufferedReader is instantiated using it. The data is read from this stream and displayed to the screen. Simple yet again!


Archived Comments

1. icojdvizogun
View Tutorial          By: icojdvizogun at 2017-09-12 00:05:33

2. Larryhaw
View Tutorial          By: Larryhaw at 2017-08-04 04:14:22

3. im blue da ba dee da ba daa da da ba dee da ba da da ba dee da ba daa
View Tutorial          By: blue at 2017-01-16 14:43:07

4. hai iam design for the claint server multiplayer game. to very useful of the site
View Tutorial          By: janakiraman.mca at 2016-11-11 08:03:54

5. sir, i need java code to display position and velocity in one system and through TCP/IP connection u
View Tutorial          By: Sandhya Yadav at 2015-08-20 07:16:04

6. Very nice tutorial :)

I have tested to modify this very short example for to can ha

View Tutorial          By: yannoo95170 at 2015-06-18 00:30:26

7. Best Example sir
View Tutorial          By: Hiren Dangar at 2015-04-23 06:55:26

8. hey im a novice in java...so i have to make a connection to another machine and send data using tcp/
View Tutorial          By: newbee at 2015-04-15 13:21:55

9. hey good code woww. this code lot of help me much thanks
View Tutorial          By: vaibhav malpani at 2015-03-25 05:48:50

10. its great!!!!
View Tutorial          By: safrgdg at 2015-02-12 10:10:07

11. any one help i want to create servermail apllication,5 client mail each other.
simple client

View Tutorial          By: Nouman at 2014-10-28 05:10:15

12. what the fuck????????????????????????????????????????
View Tutorial          By: goli at 2014-08-21 07:12:07

13. @Brian You surely can deploy your server code class. However, it does not require any web/ applicati
View Tutorial          By: Ayush at 2013-06-10 13:22:38

14. Hello, this is a very good post. I'm a newbee in Java in general, so pardon my question if it sounds
View Tutorial          By: Brian at 2013-04-11 09:07:33

15. Dude how did you used out.print() method it is giving me error
View Tutorial          By: Hardik at 2013-02-18 15:37:09

16. Here is i want some help for IM System on client server protocol can you help me ? please your email
View Tutorial          By: Arryan Chudhary at 2013-01-20 19:46:01

17. Hi,
I am designing a client server multiplayer game for android device. I need some help to l

View Tutorial          By: Varun Gupta at 2012-10-15 00:01:57

18. This is one of the most impotent , Helpful , Easy , & Great Program . Thank You vary much.
View Tutorial          By: Sujay Mandal at 2012-09-21 16:24:06

19. Hi I would like to get help with a client-server database app. My server and client work, but i do n
View Tutorial          By: lolaFireBird at 2012-06-29 08:04:31

20. Extremely Good Example. :)
View Tutorial          By: Lab-Rat ( facebook.com/kagisokgs ) at 2012-05-06 20:12:19

21. very good example..
View Tutorial          By: vignesh.m at 2010-06-16 05:00:02

22. Sir!
I want the source code for receiving SMS from GSM/CDMA mobile phons

View Tutorial          By: Anupam Shukla at 2010-04-30 00:09:25

23. i am run code this rectify this error please some ideas put me
.\SerialParameters.java:368:

View Tutorial          By: indiran at 2010-01-28 01:45:56

24. I was awe with the information above. It was well stated, I learned a lot about the java script. I t
View Tutorial          By: Lillie Clemons at 2009-10-22 07:28:44


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial