Java
Chilkat2 Java
Receive a 16-bit Integer from a Socket
See more Socket/SSL/TLS Examples
Demonstrates Socket.ReceiveInt16, which reads exactly two bytes as a 16-bit integer and stores the result in the ReceivedInt property. Byte order and signedness are selectable.
Background. Fixed-size integers and length prefixes are common building blocks for application-defined binary protocols. Byte order is selectable, with big-endian being network byte order.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Socket;
public class ChilkatExample {
public static void main(String[] args) {
Socket socket = new Socket();
// Connect to the server using TLS.
boolean bTls = true;
int maxWaitMs = 5000;
try {
socket.connect("example.com", 5000, bTls, maxWaitMs);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Read exactly two bytes as a 16-bit integer and store the result in the ReceivedInt property.
// The 1st argument selects byte order (true = big-endian); the 2nd selects unsigned interpretation.
boolean bBigEndian = true;
boolean bUnsigned = false;
try {
socket.receiveInt16(bBigEndian, bUnsigned);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Received 16-bit integer: " + socket.getReceivedInt());
}
}