Skip to content

Instantly share code, notes, and snippets.

@umit
Created August 9, 2019 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umit/22f91067563aa2e420fa0e325a4b72f8 to your computer and use it in GitHub Desktop.
Save umit/22f91067563aa2e420fa0e325a4b72f8 to your computer and use it in GitHub Desktop.
BasicTcpClient
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
public final class BasicTcpClient implements AutoCloseable {
private static final int READ_BUF_LEN = 4096;
private final Socket socket;
public BasicTcpClient(final String host, final int port) throws IOException {
this.socket = new Socket(host, port);
}
public byte[] sendAndReceive(final byte[] data) throws IOException {
send(data);
return receive(READ_BUF_LEN);
}
private void send(final byte[] data) throws IOException {
socket.getOutputStream().write(data);
}
private byte[] receive(final int bufLen) throws IOException {
final byte[] buf = new byte[bufLen];
final int len = socket.getInputStream().read(buf);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
if (len > 0) {
out.write(buf, 0, len);
}
return out.toByteArray();
}
@Override
public void close() throws Exception {
this.socket.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment