Created
April 2, 2014 19:04
-
-
Save ajhodges/9940869 to your computer and use it in GitHub Desktop.
Receive delimited protobuf message in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private byte readByte() { | |
ByteBuffer byteBuffer = ByteBuffer.allocate(1); | |
timeout.start("Timed out during protocol buffers message parsing"); | |
try { | |
int bytesRead = 0; | |
while(bytesRead==0) | |
bytesRead+=client.read(byteBuffer); | |
} catch (IOException e) { | |
//if (running) testMenu.createErrorDialog("Error", "Error parsing protobuf message", null); | |
return 0; | |
} | |
if(timeout != null) | |
timeout.stop(); | |
return byteBuffer.get(0); | |
} | |
public int readRawVarint32() { | |
byte bite = readByte(); | |
int result = bite & 0x7f; | |
int recv_bytes = 1; | |
while ((bite & 0x80)!=0){ | |
bite = readByte(); | |
if(bite<0){ | |
return 0; | |
} | |
recv_bytes++; | |
result |= (bite & 0x7f) << 7*(recv_bytes-1); | |
if ((bite & 0x80) == 0) { | |
return result; | |
} | |
} | |
return result; | |
} | |
protected ByteBuffer readProtobufMessage(){ | |
ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); | |
try { | |
//read varint32 delimiter | |
int delim = readRawVarint32(); | |
//use delimiter to read the rest of the message (handle partial recvs) | |
int bytesRead = 0; | |
timeout.start("Timed out during protocol buffers message parsing"); | |
while (bytesRead < delim && running) { | |
bytesRead += client.read(byteBuffer); | |
} | |
} catch (IOException e) { | |
//if (running) testMenu.createErrorDialog("Error", "Error parsing protobuf message", null); | |
return null; | |
} | |
if (timeout != null && timeout.stop()) return null; | |
return running ? byteBuffer : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment