Important alert: (current site time 7/15/2013 4:15:03 PM EDT)
 

article

Sockets and You

Email
Submitted on: 8/7/2000 3:34:18 AM
By: Tim Fischer 
Level: Intermediate
User Rating: By 7 Users
Compatibility: Java (JDK 1.1)
Views: 28783
author picture
(About the author)
 
     Have you ever wanted to create a chat program in Java? Well now you can with the one and only Socket!

 
 
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.
				


It seems we meet again. Or for the first time perhaps? Either way, I’ve come to enjoy your company. So lets talk over some Java. Remember to include the java.net and java.io packages!

 

You want to learn about sockets? Here are there basic steps to help that go throw the connection process:

 

1) Server (Tim) - Creates a new socket listening on port 4444.

 

2)Client (Chris) – Creates a new socket connecting to Tim on port 4444.

 

3) Data transfer begins.

 

 

Initializing a client socket looks like this.

 

Socket clientSocket = null;

clientSocket = new Socket("Tim", 4444);

This socket is connecting to a computer called Tim on port 4444. Now, Tim can be either the name of a computer on a network or an IP address. But before a client connects to a server socket, there has to be a server socket.

 

Socket serverSocket = null;

serverSocket = new Socket(4444); //Notice no user to connect to this time.

serverSocket.accept(); //Accept a client.

 

Not too hard is it? Now lets explain step three: Data Transfer.

 

From the socket you must receive input and you must send output. Clear? Good. To do this you must declare a PrintWriter for output and a BufferedReader for input. The following good is used for both a client and a server socket. For the sake of simplicity I will use a client socket.

 

PrintWriter out = null;

BufferedReader in = null;

Socket clientSocket = null;

 

clientSocket = new Socket("Tim", 4444);

out = new PrintWriter(clientSocket.getOutputStream(), true); //get the socket’s ouput

in = new BufferedReader( new inputStreamReader( clientSocket.getInputStream() ) ); //get the socket’s input

 

Looking back, I think I overdid the color. Oh well. All you really need to look at are the last two lines. The PrintWriter out will be the new front door for the socket’s output. Calling out.println(“Hello”) would send the string hello to the server. Not too hard. I am going to finish this showing you how to use a loop to receive information.

 

PrintWriter out = null;

BufferedReader in = null;

Socket clientSocket = null;

String fromServer;
 

 

clientSocket = new Socket("Tim", 4444);

out = new PrintWriter(clientSocket.getOutputStream(), true);

in = new BufferedReader(new inputStreamReader( clientSocket.getInputStream() ) );

 

while ((fromServer = in.readLine()) != null) { //Loop while we are still getting messages
System.out.println("Server: " + fromServer); //Display message we got

}

out.close();
in.close();
clientSocket.close();
 

I know right now some people aren’t going to understand this article. If you read it and don’t know how to make a chat program then you need to read some more tutorials. I suggest going to http://java.sun.com/ for more help. Email me with feedback type stuff – Tim Fischer

 

 


Report Bad Submission
Use this form to tell 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 Intermediate 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

8/8/2000 4:04:26 AMdannyboy

Short, succinct, simple and useful. If only more submissions were this good.
(If this comment was disrespectful, please report it.)

 
8/10/2000 6:50:14 PMIan Ippolito

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

 
5/23/2001 9:39:11 PM$t0rm

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

 
5/27/2001 9:26:15 PM$t0rm

Wait, sorry, that's PrintStream that's buggy...
(If this comment was disrespectful, please report it.)

 
8/13/2001 2:06:16 PMSquirrel

you should warn the newbies (myself included) about the millions of try{} and catch{} blocks involved with this. :-P
(If this comment was disrespectful, please report it.)

 
10/4/2001 8:45:32 PMRoman Dubov

I get this error when I try to compile this in Windows:
uscl.java:15: cannot resolve symbol
symbol : class inputStreamReader
location: class uscl
in = new BufferedReader(new inputStreamReader
^
1 error
---
Please get back to me, my e-mail is radubov@hotmail.com
(If this comment was disrespectful, please report it.)

 
10/4/2001 9:36:05 PMRoman Dubov

For those who are interested in a bugless example of socket at work, visit this official sun's documentation page: http://java.sun.com/docs/books/tutorial/networking/sockets/readingWriting.html
---
Regards,
Roman
D.
(If this comment was disrespectful, please report it.)

 
11/10/2001 4:30:17 PMRoman Dubov

For those who are having a problem with PrintStream, simply replace the
(If this comment was disrespectful, please report it.)

 
1/20/2002 7:39:01 PMRoman Dubov

The code presented in this short tutorial is well commented and explained in plain language which makes it a valuable introductory resource for beginning network programmers. The only shortcoming of it is that the PrintWriter is not defined completely which is why most users who are unfamiliar with java.net and java.io packages have had troubles compiling it. Visit http://java.sun.com --> Documentation --> Java Tutorial --> Search (at the bottom of the page) and type in "Sockets" and then locate and click on the "What is a socket?" link. It will give you a detailed description of what a socket is and how it actually works. After you've done reading it, click "next" to be presented with a working but a bit different version of a simple socket program.
(If this comment was disrespectful, please report it.)

 
2/19/2002 7:22:10 AMShabbir

Dear sir,
Can you provide me any type of code segment which can be used to perform voice chatting.

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

 
4/12/2002 2:38:47 AMJoe

Great tutorial and I would be very appreciated if you can provide codes voice chatting and video streaming.
HELP!!! I needed for class project.
(If this comment was disrespectful, please report it.)

 
4/4/2003 12:43:20 AM

send me the source code and package
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.