File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Never  Ending  Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply locked New topic

Never Ending Threads

ramakrishna baga

Joined: Jul 19, 2006
Posts: 4
Hi friends,
Iam new to coding, in my new project we have to connect to socket and read and write continuosly.
It is not like first read or first write , depending on the conditions it should read/write.
But both the read and write threads should be up and running continuosly.
And i should maintain only one socket object throughout the project.

Iam giving you my sample code :

//This Class connect to the Server socket and read the message
public class Connect
public static void main(String[] args)
ReadSocket rs = new ReadSocket();
WriteToSocket ws = new WriteToSocket();
Socket socket = new Socket("url",portNumber);
ws.write(socket);;//Here the thread is continuosly reading from the socket and never returning back
catch(IOException ie)
//read thread
public class ReadSocket extends Thread
public void run(Socket socket){
try {

InputStream in = socket.getInputStream();

while( != -1) {
System.out.println(" Contents of the InputStream is "+in);
catch(IOException ie) {
//write socket
public class WriteToSocket extends Thread
public void write(Socket socket){

try {

OutputStream os = socket.getOutputStream();
byte[] bytes = {3,0,0,1,2,3,0,0,1,1,0,9,118,111,108,118,111,53,49,53,0,26};

}catch(IOException ie) {

1) MY PROBLEM IS iam not able to write any more as the ReadSocket is continuosly reading the socket and it will never end and it should not.
2) What i have to do if i want to continuosly read and write to a socket.

Thanks In Advance
Henry Wong

Joined: Sep 28, 2004
Posts: 20517

Please do *not* crosspost. It wastes people time and effort.

Since you already have an answer in the threads forum, I'll close this one.

[ July 20, 2006: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: Never Ending Threads
It's not a secret anymore!