aspose file tools*
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
Author

Never Ending Threads

ramakrishna baga
Greenhorn

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();
try
{
Socket socket = new Socket("url",portNumber);
ws.write(socket);
rs.run(socket);//Here the thread is continuosly reading from the socket and never returning back
}
catch(IOException ie)
{
ie.printStackTrace();
}
}
}
//read thread
public class ReadSocket extends Thread
{
public void run(Socket socket){
try {

InputStream in = socket.getInputStream();

while(in.read() != -1) {
System.out.println(" Contents of the InputStream is "+in);
}
}
catch(IOException ie) {
ie.printStackTrace();
}
}
}
//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};
os.write(bytes);

}catch(IOException ie) {
ie.printStackTrace();
}
}
}

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
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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.

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

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
wood burning stoves
 
subject: Never Ending Threads