This is probably the most basic example you can get:
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 9998);
String command = "0006303030304e43";
// the following line converts the hex command string to a byte array
byte[] bytes = ByteBuffer.allocate(8).putLong(Long.parseLong(command, 16)).array();
OutputStream out = socket.getOutputStream();
BufferedOutputStream bufferedOut = new BufferedOutputStream(out, 1024);
bufferedOut.write(bytes);
bufferedOut.flush();
InputStream in = socket.getInputStream();
int result;
while ((result = in.read()) != -1) {
System.out.print((char)result);
}
socket.close();
}
}
To understand the meaning of the string 0006303030304e43, it can be broken down as follows (in reverse order):
- 4e43 is the 2 byte command NC as hex
- 30303030 adds a 4 byte header 0000 as hex
- 0006 represents the length in hex of the comamnd and header (i.e. the length of 0000NC)
↧