Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. import java.io.ByteArrayOutputStream;
  2. import java.io.IOException;
  3. import java.net.Socket;
  4.  
  5. public final class BasicTcpClient implements AutoCloseable {
  6.  
  7. private static final int READ_BUF_LEN = 4096;
  8.  
  9. private final Socket socket;
  10.  
  11. public BasicTcpClient(final String host, final int port) throws IOException {
  12. this.socket = new Socket(host, port);
  13. }
  14.  
  15. public byte[] sendAndReceive(final byte[] data) throws IOException {
  16. send(data);
  17. return receive(READ_BUF_LEN);
  18. }
  19.  
  20. private void send(final byte[] data) throws IOException {
  21. socket.getOutputStream().write(data);
  22. }
  23.  
  24. private byte[] receive(final int bufLen) throws IOException {
  25. final byte[] buf = new byte[bufLen];
  26. final int len = socket.getInputStream().read(buf);
  27.  
  28. final ByteArrayOutputStream out = new ByteArrayOutputStream();
  29. if (len > 0) {
  30. out.write(buf, 0, len);
  31. }
  32.  
  33. return out.toByteArray();
  34. }
  35.  
  36. @Override
  37. public void close() throws Exception {
  38. this.socket.close();
  39. }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement