Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 682
  • Last Modified:

Read from socket

Hi all
I am using non blocking IO for connecting clients to IRC server. In order to do so, I read from the socket using ByteBuffer. Is it possible to read line after line instead of buffer? I need to parse each line seperatlly and It's a problem reading the information in blocks.
   
    Thanks
0
dannysh
Asked:
dannysh
  • 4
  • 4
1 Solution
 
girionisCommented:
 Yes you can. Create a BufferedReadre instead:

BufferedReader reader = new BufferedReader(new InputStreamReader(<your socket variiable>.getInputStream()));

  Then use it like:

  String line = reader.readLine();

  to read the data line by line.

  Hope it helps.
0
 
dannyshAuthor Commented:
Hi girionis
Can I use BufferedReader in socketChannel in order to read from the socket? I think you can't do it am I right? I am using socketChannel to read from the socket.
0
 
girionisCommented:
 Hmmm. I really do not know. I am not very familiar with the nio package. Maybe if you take a look at the documentation will help you.

  Hope it helps.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
girionisCommented:
 Something else you could do is to read the characters one by one until you find the newline character ('\n') and then append it to a string. Since a new line characters indicates the end of the line then I guess it would be equal as reading a whole line using BufferedReader's readLine() method.

  Hope it helps.
0
 
dannyshAuthor Commented:
Hi girionis
reading char by char can be very slow specially when there are huge number of sockets.
   
0
 
Venci75Commented:
I would say - this is the only way to search for '\n' character. The BufferedReader is doing the same. To improve the performance of this reading - wrap the socket stream with a BufferedInputStream:

java.io.BufferedInputStream in = new java.io.BufferedInputStream(<your socket variiable>.getInputStream());

 
0
 
dannyshAuthor Commented:
Hi Venci75
As far as I know the architucture of socketChannel and Selector does not allow you using the BufferedInputStream for reading the information.
I think I will read the information into ByteBuffer and parse this buffer looking the /n char which will indicate new line.
It is not possible using BufferedInputStream.
 
0
 
dannyshAuthor Commented:
I used this idea.
  Thanks
0
 
girionisCommented:
 Thank you for the points dannysh. I am glad I helped :-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now