Bookmark Topic Watch Topic
  • New Topic

Never Ending Threads

 
ramakrishna baga
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Marshal
Pie
Posts: 21489
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
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 ]
 
    Bookmark Topic Watch Topic
  • New Topic