Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple socket client listening to data from server.  RSS feed

 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm learning how to build Socket client that listen and do some processing based on what sent from server.
--> The server will send data. The client will just wait and listen. If there's some data sent, then it will process the data.

I'm trying to build from this simple example:
http://www.exampledepot.com/egs/java.net/ReadFromSocket.html?l=rel

So I build it like this below. It doesn't seem an elegant solution for me. This will keep looping and looping forever.
Can someone please advice a good way to do this? Thanks in advance for the help.

 
Joe Ess
Bartender
Posts: 9425
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want the client to continuously listen for data, it has to loop forever. What else does your client have to do?
 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is what I'm doing ok?

I'm not sure about this part:
[CODE]
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
while ( true )
{
dataInputStream.readFully(temp1, 0, 8);
.....
}
[CODE]
Is it enough to call socket.getInputStream() one time and then just looping forever to call dataInputStream.readFully()? I notice it uses some heavy CPU often. I think it's because the infinite loop.
Is it a good construct of a Socket Listener?

I'm not sure if this helpful info or not:
The server doesn't send data in a predictable period.
 
Joe Ess
Bartender
Posts: 9425
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would expect your readFully call to block until there's data. The only time you see a significant CPU load should be when it's actually processing data.
How much data are you expecting? If it's more than 8 bytes you may want to make the byte array larger.
[ October 29, 2008: Message edited by: Joe Ess ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!