Created
August 9, 2019 08:37
-
-
Save umit/22f91067563aa2e420fa0e325a4b72f8 to your computer and use it in GitHub Desktop.
BasicTcpClient
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
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