Skip to content

Instantly share code, notes, and snippets.

@huylenq
Created November 3, 2017 06:02
Show Gist options
  • Select an option

  • Save huylenq/55082c9508238c6f63886c0d5e09ee33 to your computer and use it in GitHub Desktop.

Select an option

Save huylenq/55082c9508238c6f63886c0d5e09ee33 to your computer and use it in GitHub Desktop.
package com.huyle;
import java.io.IOException;
public class SocketTDExercise {
private static final int MESSAGE_SIZE = 8;
private HLSocket socketClient;
/**
* An artificial terminal API to fetch the next fixed-length
* message from an endpoint with the provided address.
*/
public byte[] nextMessage(String address) throws IOException {
byte[] buf = new byte[MESSAGE_SIZE];
int bufOffset = 0;
int actualRead = 0;
SocketConnection socket = null;
try {
socket = socketClient.connect(address);
while (bufOffset < MESSAGE_SIZE) {
actualRead = socketClient.readFromSocket(
socket,
buf,
bufOffset,
MESSAGE_SIZE - actualRead);
if (actualRead == -1) {
int errorCode = socketClient.readFromSocket(socket, null, 0, 0);
throw new IOException(String.format(
"Failed to read data completely from a socket: %s. "
+ "Error code: %d", MESSAGE_SIZE, errorCode));
} else if (actualRead == 0 && bufOffset < MESSAGE_SIZE) {
throw new IOException(String.format(
"EOF before reaching the requested size %d", MESSAGE_SIZE));
}
bufOffset += actualRead;
}
} finally {
if (socket != null) {
socket.close();
}
}
return buf;
}
interface SocketConnection {
void close();
}
interface HLSocket {
SocketConnection connect(String address);
int readFromSocket(SocketConnection connection,
byte[] buffer,
int bufferOffset,
int requestSize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment