TCP Server and TCP Client in Java
By: Ashish Myles in Java Tutorials on 2009-10-15
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!
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Read a file having a list of telnet commands and execute them one by one using Java
Open a .docx file and show content in a TextArea using Java
Step by Step guide to setup freetts for Java
Of Object, equals (), == and hashCode ()
Using the AWS SDK for Java in Eclipse
DateFormat sample program in Java
concurrent.Flow instead of Observable class in Java
Calculator application in Java
Sending Email from Java application (using gmail)
Comments