Overgram/lib/src/main/java/io/github/lonamiwebs/overgram/network/TcpClient.java

47 lines
1.2 KiB
Java

package io.github.lonamiwebs.overgram.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClient {
private Socket socket;
public void connect(final String ipAddress, final int port) throws IOException {
socket = new Socket(ipAddress, port);
}
public void close() {
try {
socket.close();
} catch (IOException ignored) {
}
}
public byte[] read(final int length) throws IOException {
final InputStream in = socket.getInputStream();
final byte[] result = new byte[length];
int index = 0;
while (true) {
final int count = in.read(result, index, result.length - index);
if (count == -1) {
throw new IOException("Connection closed");
}
index += count;
if (index == result.length) {
return result;
}
}
}
public void write(final byte[] bytes) throws IOException {
final OutputStream out = socket.getOutputStream();
out.write(bytes);
out.flush();
}
}