TCP Server and TCP Client in Java

By: Ashish Myles Emailed: 1729 times Printed: 2337 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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!

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(15)


1. View Comment

i am run code this rectify this error please some ideas put me
.\SerialParameters.java:368: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
return SerialPort.FLOWCONTROL_XONXOFF_IN;
^
.\SerialParameters.java:371: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
return SerialPort.FLOWCONTROL_RTSCTS_IN;
^
.\SerialParameters.java:374: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
return SerialPort.FLOWCONTROL_RTSCTS_OUT;
^
.\SerialParameters.java:376: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
return SerialPort.FLOWCONTROL_NONE;
^
.\SerialParameters.java:387: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
case SerialPort.FLOWCONTROL_NONE:
^
.\SerialParameters.java:389: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
case SerialPort.FLOWCONTROL_XONXOFF_OUT:
^
.\SerialParameters.java:391: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
case SerialPort.FLOWCONTROL_XONXOFF_IN:
^
.\SerialParameters.java:393: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
case SerialPort.FLOWCONTROL_RTSCTS_IN:
^
.\SerialParameters.java:395: cannot find symbol
symbol : variable SerialPort
location: class SerialParameters
case SerialPort.FLOWCONTROL_RTSCTS_OUT:
^


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

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
3. View Comment

very good example..

View Tutorial          By: vignesh.m at 2010-06-16 05:00:02
4. View Comment

Hi I would like to get help with a client-server database app. My server and client work, but i do not know how to send data from the database on the server to the client and to access the SQL server database from the client. please can you send me an example or help.

View Tutorial          By: lolaFireBird at 2012-06-29 08:04:31
5. View Comment

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
6. View Comment

Hi,
I am designing a client server multiplayer game for android device. I need some help to learn more on How can i achieve the task.


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

Dude how did you used out.print() method it is giving me error

View Tutorial          By: Hardik at 2013-02-18 15:37:09
8. View Comment

Hello, this is a very good post. I'm a newbee in Java in general, so pardon my question if it sounds a bit foolish. As I understand the Server code has to infinitely run and keep on listening to requests from the client. So where in a typical java app can I place this server coding class so that it can keep on listening? I'm using glassfish as my app server. Thank you in advance.

View Tutorial          By: Brian at 2013-04-11 09:07:33
9. View Comment

@Brian You surely can deploy your server code class. However, it does not require any web/ application server to run on. Reason being, the socket program talks with your socket directly and to keep listening from your server, you juts need to run it as a simple java program from either bash or cmd.

View Tutorial          By: Ayush at 2013-06-10 13:22:38
10. View Comment

any one help i want to create servermail apllication,5 client mail each other.
simple client server code avalible but i dont know how can i add.


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

its great!!!!

View Tutorial          By: safrgdg at 2015-02-12 10:10:07
12. View Comment

hey good code woww. this code lot of help me much thanks

View Tutorial          By: vaibhav malpani at 2015-03-25 05:48:50
13. View Comment

Best Example sir

View Tutorial          By: Hiren Dangar at 2015-04-23 06:55:26
14. View Comment

Very nice tutorial :)

I have tested to modify this very short example for to can handle multiples clients with a near infinite loop into the server's and client's parts but this don't work very well :(
(each client seem to be blocked after about 40 messages)


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

sir, i need java code to display position and velocity in one system and through TCP/IP connection using socket pgrming should be able to change values of them in another system using celscript and output should be shown in open source calld celestia.........pls i need some assistance urgently required for my project.......

View Tutorial          By: Sandhya Yadav at 2015-08-20 07:16:04

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ashish Myles
TCP Server and TCP Client in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
indexOf( ) and lastIndexOf( ) in Java
Student marks calculation program in Java
Method Overloading (function overloading) in Java
FileReader and FileWriter example program in Java
Vector example in Java
wait(), notify() and notifyAll() in Java - A tutorial
InetAddress Example program in Java
Calendar - sample program in Java
Hashtable example in Java
Method Overriding in Java
Sample Java program shows how to write to COM port using Java.
What is Java?
float vs double data types in Java
TreeMap example in Java
Most Emailed Articles (in Java)
Vector in Java - Sample Program
Use of return statement in Java
instanceof operator example in Java
3-D Secure Payment or 3DS - (3-Domain Secure Payment)
What is a Java Package and how to use it?
How to use Iterator in Java
J2EE Components
The java Buzzwords
The Basic Structure of a Simple Java program
Java Chat Client Sample Applet
MultiLevel Inheritance sample in Java
Taking the size of an Array at runtime & generate random numbers to populate the Array
What is JasperReports?
java.lang.reflect package
Applet Notinited : Applet xxxxxxxxxxxx notinited