Java/ Javascript Stats:

How to support the site


Site Wide Message: (current site time 5/23/2011 10:31:39 PM EDT)
  • A big thank you to Mr. Clinton Williams who made an incredibly generous donation to Planet Source Code's T1 fund. On behalf of myself and all the users of Planet Source Code, thank you Mr. Williams for helping us keep the site a free resource for all!
 

Socket Programming Using Java

Print
Email
article
Submitted on: 4/28/2005 12:58:54 AM
By: Karthik Veeramani 
Level: Beginner
User Rating: By 72 Users
Compatibility:Java (JDK 1.1), Java (JDK 1.2), Java (JDK 1.3), Java (JDK 1.4), Java (JDK 1.5)

Users have accessed this article  67648 times.
 
(About the author)
 
     This tutorial will make you understand what sockets are, and will help you to start coding simple networking applications using Java.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

SOCKET PROGRAMMING USING JAVA

If you find this tutorial good enough, please vote for me (use the Your Vote! section at the end of this page)

So you want to start doing some network programming with Java... You've come to the right place. I'll introduce you to the interesting world of Java sockets. By the end of this tutorial, you should be able to understand what sockets are and how to build simple Java applications using sockets.

Whats a socket?

Don't tell me you've never chatted on those instant messengers like yahoo, msn and aol. But its OK if you never understood what goes on behind the scene; after all, thats what we are here for. Lets say you've installed one of those instant messengers on your computer. After you run it and enter your user name and password, the messenger tries to connect to its server (say, the yahoo server). What exactly does this 'connect' mean?

Every computer on a network has an IP address. This address is like your house address, something that identifies your computer uniquely, allowing others to communicate with your computer. I wont go much into IP addresses, but let me just tell you that an IP address looks something like this - 64.104.137.158 - a set of numbers separated with dots. However, some computers with rich owners will also choose to have a domain name in addition to this sick looking number, so that people can easily identify them. A domain name looks far more sane - like www.yahoo.com. There are some special computers on the Internet, whose sole purpose in life is to translate the domain name to IP address and vice versa.

Now, you know that many programs can run on the same computer, don't you? Lets say that, there are some 10 programs running on a certain computer. To add to the confusion, lets say all of them are waiting for other computers to contact them. Imagine it like this - 10 of you share a big office space and a single telephone - and all of you expect calls from your own clients. How will you handle this? Perhaps appoint one person who'll hand over the call to the right person. Possible, but an undeniable menace. This will mean, when one of you take the call, other clients will not be able to reach the rest of you. Besides, its a pain to have a person route the calls to the right people. You must have guessed what I'm heading at - if all those programs running on a single computer proudly ask their clients to contact them on a certain IP address, their clients are not going to be pleased. The idea is... having a separate IP address per program, right? WRONG. Thats out of question. Its like asking for a separate office for each of you. Wont separate phone numbers suffice? Yes. In networking parlance, we call these 'separate phone numbers' as ports. A port is just a simple number - each program running on the same computer can choose to have a unique port number to identify itself to the outside world. REMEMBER - these ports are not slots on your computer hardware - dont think you can find them if you try hard enough. They are just logical numbers. Now the point should be clear. We have an IP address that lets the other computers look for a certain computer on the network. And we have a port number that'll identify a certain program running on that computer. Understand that, two programs running on different computers CAN use the same port number. Two houses on different streets can have the same house number, can't they? So, finally, we are almost there - just to scare you a bit, lets derive a formula -

An IP address = uniquely identifies a computer on the network. A port number = uniquely identifies a program running on a computer.

Adding the above equations,

An IP address + A port number = _______

In other words, A _____ = uniquely identifies a program on the network

If you guessed it right, thanks, my effort didn't go waste. If you didn't, no problem, go back and read from the beginning, or google for a better tutorial. The ____ is... SOCKET!

To summarize, a socket is a combination of an IP address and a port. A socket address lets other computers on the network locate a certain program running on a certain computer. You may represent a socket address like 64.104.137.58:80, where 64.104.137.58 is the IP address and 80 is the port number.

How to program

Enough of theory talk. Lets get into some action now. We are going to write some very simple Java code, that'll demonstrate the use of sockets. Here is what is going to happen -

1) One Java program will try to connect to another Java program (which is desperately waiting for someone to contact it). Lets call the first program as Client, and the second as Server.
2) Once connected, the client program is going to accept whatever you type, and send it dutifully to the server program.
3) The server is going to send back the same text to the client, just to show that it is least interested in doing such an uninteresting thing.
4) The client, after getting back the same text from the server, is going to throw it on your face, showing you what the server thinks about you.

Ready? Lets get started. Note that, I wont be teaching you Java programming from scratch, I'll explain only the socket-related portions of the code.

Create 2 fresh Java programs and call them Server.java and Client.java. I'll paste the code below, but don't be scared, I'll explain.

Server.java
 
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] ar) {
 int port = 6666; // just a random port. make sure you enter something between 1025 and 65535.
 try {
 ServerSocket ss = new ServerSocket(port); // create a server socket and bind it to the above port number.
 System.out.println("Waiting for a client...");
 Socket socket = ss.accept(); // make the server listen for a connection, and let you know when it gets one.
 System.out.println("Got a client :) ... Finally, someone saw me through all the cover!");
 System.out.println();
 // Get the input and output streams of the socket, so that you can receive and send data to the client.
 InputStream sin = socket.getInputStream();
 OutputStream sout = socket.getOutputStream();
 // Just converting them to different streams, so that string handling becomes easier.
 DataInputStream in = new DataInputStream(sin);
 DataOutputStream out = new DataOutputStream(sout);
 String line = null;
 while(true) {
 line = in.readUTF(); // wait for the client to send a line of text.
 System.out.println("The dumb client just sent me this line : " + line);
 System.out.println("I'm sending it back...");
 out.writeUTF(line); // send the same line back to the client.
 out.flush(); // flush the stream to ensure that the data reaches the other end.
 System.out.println("Waiting for the next line...");
 System.out.println();
 }
 } catch(Exception x) {
 x.printStackTrace();
 }
 }
 }
 
Client.java
 
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] ar) {
 int serverPort = 6666; // make sure you give the port number on which the server is listening.
 String address = "127.0.0.1"; // this is the IP address of the server program's computer. // the address given here means "the same computer as the client".
 try {
 InetAddress ipAddress = InetAddress.getByName(address); // create an object that represents the above IP address.
 System.out.println("Any of you heard of a socket with IP address " + address + " and port " + serverPort + "?");
 Socket socket = new Socket(ipAddress, serverPort); // create a socket with the server's IP address and server's port.
 System.out.println("Yes! I just got hold of the program.");
 // Get the input and output streams of the socket, so that you can receive and send data to the client.
 InputStream sin = socket.getInputStream();
 OutputStream sout = socket.getOutputStream();
 // Just converting them to different streams, so that string handling becomes easier.
 DataInputStream in = new DataInputStream(sin);
 DataOutputStream out = new DataOutputStream(sout);
 // Create a stream to read from the keyboard.
 BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
 String line = null;
 System.out.println("Type in something and press enter. Will send it to the server and tell ya what it thinks.");
 System.out.println();
 while(true) {
 line = keyboard.readLine(); // wait for the user to type in something and press enter.
 System.out.println("Sending this line to the server...");
 out.writeUTF(line); // send the above line to the server.
 out.flush(); // flush the stream to ensure that the data reaches the other end.
 line = in.readUTF(); // wait for the server to send a line of text.
 System.out.println("The server was very polite. It sent me this : " + line);
 System.out.println("Looks like the server is pleased with us. Go ahead and enter more lines.");
 System.out.println();
 }
 } catch(Exception x) {
 x.printStackTrace();
 }
 }
 }
 
Compile it with
 javac Server.java Client.java 
Open two command windows (DOS prompts). In one of those, enter
 java Server
and in the other,
 java Client

(in that order!)

Type something on the client window and press enter. Observe both windows and see what happens. Finally, press ctrl-C to kill the programs.

Explanation

Lets delve into the code now. You must have got some idea looking at the comments, still, lets try to analyze a few critical lines.

The server code has the lines

ServerSocket ss = new ServerSocket(port);
Socket socket = ss.accept();

A ServerSocket class is slightly different from the Socket class. The Socket class is exactly what you think.. well, it represents a socket. The ServerSocket class is mainly for allowing a program to listen for connections from clients. You create it by assigning it a port number on which it can work on. Once created, you need to call its accept() method. This method will make the program listen on the given port for connections. It hangs there until it gets a client. Once a client gets in touch, it creates a normal Socket object, and hands it over to you so that you can start doing all the socket operations you want. Note that, this Socket object returned by accept() method, represents the other end of the connection. After all, if you want to send some data to the client, you can't write it to your own socket!

Next is the Socket class. You create the Socket object by passing an IP address and a port number. Java gives you the InetAddress class to represent an IP address, so you better go their way and use it. To create an InetAddress object that represents an IP address, you can use this method -

InetAddress ipAddress = InetAddress.getByName(address);

Note that in our program, we have 127.0.0.1 for the address. This address is a special address called loopback address. Don't panic, it is just an address that represents the local computer. If you intend to run the client and server on different machines, use the correct IP address of the server.

Once the InetAddress is created, we create the Socket, Socket socket = new Socket(ipAddress, serverPort);

Once you have the Socket object, you can get the input and output streams of the socket. The input stream will let you read from the socket and the output stream lets you write to the socket.

InputStream sin = socket.getInputStream(); OutputStream sout = socket.getOutputStream();

The below lines are just for converting the above to different types of streams. So that it becomes easy for us to deal with String objects. This has got nothing to do with networking.

DataInputStream in = new DataInputStream(sin); DataOutputStream out = new DataOutputStream(sout);

The rest is easy. Because it just deals with the stream objects you created, and not with sockets. You can use your favorite stream, call your favorite methods, somehow ensure the data reaches the other end. Read up on streams if you are not comfortable.

I hope I enlightened you all by introducing the fabulous world of network programming. Feel free to shoot your questions, I'll answer them if I can. You can also give me your valuable feedback, suggestions, or the mistakes you found in this tutorial.

And yes, if you found this useful, go to that Your Vote! section below and vote for me!


Other 2 submission(s) by this author

 

 
 Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:
 
Your Vote!

What do you think of this article(in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor
See Voting Log
 
Other User Comments
5/3/2005 10:20:00 PM

can u give any example of any system,i means a client-server system that use socket programming use java.tq
(If this comment was disrespectful, please report it.)

 
5/6/2005 1:05:11 AMKarthik Veeramani

Billions... The chat programs usually have a single server and multiple clients. You browsing the web with your web browser is a client-server model, where your browser is the client and the website you visit is the server.
(If this comment was disrespectful, please report it.)

 
5/9/2005 4:26:48 AMShyam Prasad Murarka

Yes, thanks very much. This tutorial is even better than Sun's tutorial on Sockets. it completely removed my doubts on Sockets. If you could do the same work for other topics like Polymorphism (with lots of examples) it would be nice.
(If this comment was disrespectful, please report it.)

 
5/9/2005 4:45:21 AMKarthik Veeramani

Thanks very much, I'll try my best to spend time on other topics. Perhaps you could let me know a few things that you find tricky, and I'll see if I know them well.

Also, you may want to check out my latest submission, a software that exports your gmail address book -
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4793&lngWId=2

(If this comment was disrespectful, please report it.)

 
5/12/2005 6:07:06 AM

A very nice tutorial, nice code and explained very well. Will definitely keep an eye for further tutorials from this guy.
(If this comment was disrespectful, please report it.)

 
5/14/2005 2:47:54 AMKarthik Veeramani

Check out my latest tutorial on polymorphism - http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4811&lngWId=2
(If this comment was disrespectful, please report it.)

 
6/6/2005 3:26:27 AM

Great Tutorial...
easy to understand
(If this comment was disrespectful, please report it.)

 
6/13/2005 9:50:44 AM

Hey, actually , i was not having any idea about sockets . After reading this tutorial, i have got a clear idea about what a socket is. This tutorial is really excellent, i have reported it to all my friends. I think the example given is the best of many more examples given in other sites and books. Excellent work by the author for beginners like me!!Go on!!
(If this comment was disrespectful, please report it.)

 
6/29/2005 3:48:12 AM

a very tutorial for beginners like me well would like to have an idea about connection of a Java Client to a C++ client.
(If this comment was disrespectful, please report it.)

 
6/29/2005 4:00:55 AMKarthik Veeramani

Im not sure what kindof connection u want, but u may want to look at JNI to call java code in c++ or vice versa.
(If this comment was disrespectful, please report it.)

 
10/9/2005 7:52:12 AMAnkur

its very gud, bit still the later part of your explanation wasn't much clear, the part which explained the code.....
(If this comment was disrespectful, please report it.)

 
10/9/2005 11:47:08 AMKarthik Veeramani

Thanks for the feedback. Yes, u'll find the code a lil difficult if u r not familiar with basic java. If u have any specific difficulties, u can email me. I'll be glad to help.
(If this comment was disrespectful, please report it.)

 
1/13/2006 6:46:23 AMJoe

Nice article...cleared my doubts on Sockets
(If this comment was disrespectful, please report it.)

 
1/18/2006 9:09:43 PMWhiteShadoW

I can say that this is the best tutorial I have yet read, I have been trying to find something that talks about socket in a simple manner, thanks to your article I was saved in the last minute and was able to do my assigned task.

I was wondering if you have any publications, I really would like to have the chance to read more of your works, thanks for such a fune peice of art.
(If this comment was disrespectful, please report it.)

 
2/18/2006 12:19:46 AM

nice code

(If this comment was disrespectful, please report it.)

 
2/27/2006 1:37:34 PMnagarajan.s


Nice code.but needed constant approach to complexity
(If this comment was disrespectful, please report it.)

 
8/14/2006 6:44:14 AMdarren

i dare to say you had did a great job.Simple and clear example which lead me to understand about the Socket within 10mintues. Thanks and i really appreaciated it.
(If this comment was disrespectful, please report it.)

 
8/29/2006 2:41:46 AMJaya Prakash K G

When compared with other sites It gives me very quick and clear understanding about the bascics of the socket programming. Thank you, very much.
(If this comment was disrespectful, please report it.)

 
12/21/2006 5:01:22 AMJohn Bright. J

Hi,

Well explained. I need a help such that, I need a Server that should wait for the clients to communicate. As a novice I need help.
(If this comment was disrespectful, please report it.)

 
4/13/2007 4:09:01 AMVinutha

hello Sir... I have checked out the application(Server and Clien) u have explained but its not executing... its compiling but not rinning... C:\socketpgms>javac Client12.java C:\socketpgms>java Client12 Any of you heard of a socket with IP address 127.0.0.1 and port 6666? java.net.SocketException: Software caused connection abort: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) at Client12.main(Client12.java:13) C:\socketpgms> Can u suggest me wat the mistake i have done........
(If this comment was disrespectful, please report it.)

 
4/13/2007 1:05:06 PMKarthik Veeramani

One possibility is that some other program, like Windows Firewall, or some anti virus you have installed is conflicting with this. Disable everything and try. Another possibility is, the port your are using could've been in use already (I think the error message is different for this situation, still it is worth checking). To check if another program is using your port, you can run "netstat -a" from dos prompt and see if your port is listed.
(If this comment was disrespectful, please report it.)

 
4/19/2007 12:21:32 PMKris Davison

A great tutorial. I have quite a good knowledge of java but i was quite interested to know about sockets. This was a great help and had me up and running in about 10 mins.
I did find some things you may like to add:
1) The ip address you have put in the code needs to be changed to the ip address of the servers computer
--if you are using this on your computer this can be found by opening a cmd dos window and typing ipconfig.
2) when complieing and running the code in a dos window make sure u find the file you have saved the Client.Java and Server.java files using cd file-name
then use "javac server.java" as it says in the tutorial.
Then when running it try this
"java -cp . Server" as this should allow the program to run more easily. I hope this might help some people out a bit.


(If this comment was disrespectful, please report it.)

 
5/13/2007 12:53:21 PM

great job!!
thanks bro
(If this comment was disrespectful, please report it.)

 
7/25/2007 2:29:58 AMyus

great explaination ! but can u give any idea to make a prog for cyber cafe monitoring sys ? ;p
(If this comment was disrespectful, please report it.)

 
11/9/2007 12:02:04 AMLeventis

Hey, wow very good work ! I try do make GUI in Netbeans but I am an amateur and I have many problems. Can you Help me?


(If this comment was disrespectful, please report it.)

 
11/11/2008 12:01:43 AMDedeepya

Its a great job...
(If this comment was disrespectful, please report it.)

 
12/8/2008 2:22:16 AMrj

xcelent work! Could somebody please sugest the line of codes should be entered to close the socket.(Instead of asking to enter more lines)Thanks.
(If this comment was disrespectful, please report it.)

 
12/29/2008 1:42:39 AMrevathi

hi,thanks for ur code...i want some more programs in networking in java...pls send it to mail id...


(If this comment was disrespectful, please report it.)

 
4/1/2009 2:33:08 PMmac

A great explaination I ever found.......
I want 2 create a lan monitoring software in java . Please help me in accomplishing this task
(If this comment was disrespectful, please report it.)

 
11/10/2009 3:03:24 AM

Hey thanks.. the article is excellent. I tried the code, works fine with 1 client... i wanted to have multiple clients. With this code, when 1 client connects the other clients are blocked.. can you please provide help on how to do that. Also can the server and client be implemented as HTTP server and client. I actually want to write a socket server program to accept HTTP data from clients. I dont know how to do that. Is there any particular HTTP data format to be used? Please help me... I am stuck on this issue... Ur help would be greatly appreciated.
(If this comment was disrespectful, please report it.)

 
11/14/2009 6:36:17 AMShreehari

Thanx so much for the tut. wish u wer a prof. at my college. ^_^

Doubt : I tried connecting two clients at the same time using ur programs. second one doesnt connect. what should i change?
(If this comment was disrespectful, please report it.)

 
11/14/2009 1:43:04 PMKarthik Veeramani

Thanks. This example won't work for multiple clients. But it is easy to find a sample by searching "java chat multiple clients" in http://www.google.com/codesearch
(If this comment was disrespectful, please report it.)

 
2/18/2010 1:15:44 PMpratik

it's a nice article

can u please explain a simple code like this for multiple client

also if one client will want to communicate with the other how is it possible

(If this comment was disrespectful, please report it.)

 
4/14/2010 2:59:21 PMMOHITH

THE ABOVE EXPLANATION AND EXAMPLE WAS VERY USEFUL.. THANK YOU FOR THE NEED.. GOOD JOB DONE SIR!!!!!!!!!!1
(If this comment was disrespectful, please report it.)

 
2/9/2011 11:58:54 AMtina

really nice work. really thanks
(If this comment was disrespectful, please report it.)

 
Add Your Feedback!

Note:Not only will your feedback be posted, but an email will be sent to the code's author from the email account you registered on the site, so you can correspond directly.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
To post feedback, first please login.