Skip to content

Commit 7ddf0c7

Browse files
swaxTooTallNate
authored andcommitted
Data read from network into a 8kb buffer, not one byte at a time so android doesn't hang
1 parent d8274b3 commit 7ddf0c7

1 file changed

Lines changed: 19 additions & 9 deletions

File tree

‎src/net/tootallnate/websocket/WebSocket.java‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ public final class WebSocket {
7070
* The 1-byte buffer reused throughout the WebSocket connection to read data.
7171
*/
7272
private ByteBuffer buffer;
73+
/**
74+
* Buffer where data is read to from the socket
75+
*/
76+
private ByteBuffer socketBuffer;
7377
/**
7478
* The bytes that make up the remote handshake.
7579
*/
@@ -107,6 +111,7 @@ public final class WebSocket {
107111
this.bufferQueue = bufferQueue;
108112
this.handshakeComplete = false;
109113
this.remoteHandshake = this.currentFrame = null;
114+
this.socketBuffer = ByteBuffer.allocate(8192);
110115
this.buffer = ByteBuffer.allocate(1);
111116
this.wsl = listener;
112117
}
@@ -118,22 +123,27 @@ public final class WebSocket {
118123
* @throws NoSuchAlgorithmException
119124
*/
120125
void handleRead() throws IOException, NoSuchAlgorithmException {
121-
this.buffer.rewind();
122-
126+
123127
int bytesRead = -1;
128+
124129
try {
125-
bytesRead = this.socketChannel.read(this.buffer);
130+
socketBuffer.rewind();
131+
bytesRead = this.socketChannel.read(this.socketBuffer);
126132
} catch(Exception ex) {}
127133

128-
if (bytesRead == -1) {
134+
if (bytesRead == -1) {
129135
close();
130136
} else if (bytesRead > 0) {
131-
this.buffer.rewind();
137+
for(int i = 0; i < bytesRead; i++) {
138+
buffer.rewind();
139+
buffer.put(socketBuffer.get(i));
140+
141+
this.buffer.rewind();
132142

133-
if (!this.handshakeComplete) {
134-
recieveHandshake();
135-
} else {
136-
recieveFrame();
143+
if (!this.handshakeComplete)
144+
recieveHandshake();
145+
else
146+
recieveFrame();
137147
}
138148
}
139149
}

0 commit comments

Comments
 (0)