Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Receiving Multiple Packets from Server Socket

Status
Not open for further replies.

justride

Programmer
Jan 9, 2004
251
US
Hello,

I am creating a client connection to a server socket that receives packets. Each time the client connects, I start a thread that reads what is available on the socket then breaks out of the thread.

I need to have that thread listen for data until the socket connection is lost. An infinite loop seems inefficient so I was wondering how this is done is the real world? How would I structure my thread run() method to sleep until new packets have arrived?

Thanks
 
I have server gui and a client gui running. The server gui sends byte streams to the client gui. when the client gui connects to the server I run a thread with the following code in the run() method. I see the first stream of data appear in my client gui, however my 2 gui's about lock up after this. I have a feeling that the client gui keeps looping, lookign for a new length byte, and the infinite loops are lagging the system.

any thoughts?

run() method:
Code:
public void run(){ 
          while (socket != null){
		try {
	              int len = is.read();
	              if(len >=0){
		              byte[] packet_array = new byte[len];
		              is.readFully(packet_array);
		              String resultdata = "";
		              for(int i=0; i<packet_array.length;i++){
		                  resultdata = resultdata+(char)packet_array[i];
		              }
		              
		              result.setText(result.getText()+"\n"+resultdata);
		          }
	              
	                  
	          }catch (UnknownHostException e) {
	              System.out.println("Read Socket - ERROR UNKOWN");
	              statusinput.setText("ERROR");
	          }catch (IOException e) {
	              System.out.println("Read Socket - ERROR in I/O");
	      	      statusinput.setText("ERROR");
	          }
	}
}
[code]
 
I guess when there is no data left, a -1 is returned for len and the while loop, loops continuously. I need the read() to wait for new data when the stream is empty. Any suggestions?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top