Quick Search for:  in language:    
ever,wanted,create,chat,program,Java,Well,wit
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
Java/ Javascript Stats

 Code: 220,465. lines
 Jobs: 92. postings

 How to support the site

 
Sponsored by:

 
You are in:
 
Login





Latest Code Ticker for Java/ Javascript.
Click here to see a screenshot of this code!vok - The vocabulary trainer
By Thorsten Stärk on 1/7

(Screen Shot)

Java, Calculator
By Rockwell on 1/4


Eatable Interface
By Rockwell on 1/4


Superclass Person
By Rockwell on 1/4


Draws Cube Function
By Rockwell on 1/4


Rectangle Class
By Rockwell on 1/4


Find Number of Upper and Lower Case Letters in a Command Line Argument String
By Rockwell on 1/4


anagrams
By Rockwell on 1/4


Text Reader with Tokenizer
By Rockwell on 1/4


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Sockets and You

Print
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)

Users have accessed this article 19131 times.
 

(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

 

 


Other 1 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.).
Reason:
 
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 AM:dannyboy
Short, succinct, simple and useful. If only more submissions were this good.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/10/2000 6:50:14 PM:Ian Ippolito
Great article!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/23/2001 9:39:11 PM:$t0rm
PrintWriter = buggy...
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/27/2001 9:26:15 PM:$t0rm
Wait, sorry, that's PrintStream that's buggy...
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/13/2001 2:06:16 PM:Squirrel
you should warn the newbies (myself included) about the millions of try{} and catch{} blocks involved with this. :-P
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/4/2001 8:45:32 PM:Roman 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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/4/2001 9:36:05 PM:Roman 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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
11/10/2001 4:30:17 PM:Roman Dubov
For those who are having a problem with PrintStream, simply replace the
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/20/2002 7:39:01 PM:Roman 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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
2/19/2002 7:22:10 AM:Shabbir
Dear sir, Can you provide me any type of code segment which can be used to perform voice chatting.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/12/2002 2:38:47 AM:Joe
Great tutorial and I would be very appreciated if you can provide codes voice chatting and video streaming. HELP!!! I needed for class project.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/4/2003 12:43:20 AM:
send me the source code and package
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

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.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | Java/ Javascript Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.