Skip to main content
gamedev.net
🔒 Locked

Java Socket Read Problem

Started by fathom88 3 replies 2.2k views
Original Post
fathom88
fathom88
Is there a max rate Java's SocketChannel can read data at? I always assumed the max rate would be whatever your hardware connection is. In my case, it's two PC's next to each other connected by an ethernet cable. I must conclude there is a problem with my read code. My server sends 2.5 MB of data to my client every 1 sec. My client seems to take 3 or 4 sec to read the 2.5 MB of data. I'm new to using the SocketChannel and assume I'm doing something wrong. Here is my read code which gets called inside my void run() with a "Thread.sleep(1)" ByteBuffer buf = ByteBuffer.allocateDirect(1024); try { // Clear the buffer and read bytes from socket buf.clear(); int numBytesRead = socketChannel.read(buf); if (numBytesRead == -1) { // No more bytes can be read from the channel socketChannel.close(); } else { //Read bytes; currently commented out to do nothing to prevent //any slow down from processing the data } } catch (IOException e) { // Connection may have been closed } I tried to increase the read buffer. I've to set my sleep to zero. Both attempts didn't speed up the read.
smr
smr
The solution is simple if you do the math...

Reading 1024 bytes every 1 millisecond: 1024000 bytes per second.
2.5 megabytes: 2621440 bytes
Time to read 2621440 bytes at 1024000 bytes per second: 2.56 seconds.

The actual time between your reads is going to be many times more than 1 millisecond depending on your hardware. But as you can see, just that one millisecond is creating a bottleneck. If you want this to go faster, use a larger buffer.

[Edited by - smr on December 10, 2008 2:59:25 PM]
fathom88
fathom88
My knee jerk reaction was to increase the buffer to 20480 and set the sleep to zero. I didn't notice a difference. I guess I could increase the buffer further. On another note, my sever app streams the 2.5 MB over the course of one sec. It does NOT send a single burst of 2.5 MB at one sec intervals.
smr
smr
Even though you're sleeping zero, the thread is suspending execution for an indeterminate amount of time. If you want this to go fast, you're going to have to read() until the buffer is empty without yielding the thread voluntarily. The issue is probably exacerbated by the socket's buffer being too full to accept any more data from the network, causing the server to block on send().
fathom88
fathom88
I'm still only getting around 1 MB a sec. I've noticed if I increase the buffer too much or lower the thread sleep to zero, the amount I read actually goes down. Why would that be?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.