53 lines
1.5 KiB
Java
53 lines
1.5 KiB
Java
package io.github.lonamiwebs.overgram.network;
|
|
|
|
import io.github.lonamiwebs.overgram.logging.Log;
|
|
|
|
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 {
|
|
Log.info("Connecting to %s:%d", ipAddress, port);
|
|
socket = new Socket(ipAddress, port);
|
|
}
|
|
|
|
public void close() {
|
|
try {
|
|
Log.info("Closing socket connection %s", socket.getRemoteSocketAddress());
|
|
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);
|
|
Log.debug("Read %d more bytes out of %d", count, 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();
|
|
Log.debug("Writing %d bytes", bytes.length);
|
|
out.write(bytes);
|
|
out.flush();
|
|
}
|
|
}
|