JavaScript
JavaScript
Receive a 4-byte Length Prefix from a Socket
See more Socket/SSL/TLS Examples
Demonstrates Socket.ReceiveCount, which reads a four-byte length prefix as a signed 32-bit integer. A return value of -1 indicates failure.
Background. Reading the length prefix first tells the application exactly how many bytes to read for the message body, which is a reliable way to know when a full message has arrived.
Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat
v11.4.0 or greater.
var success = false;
var socket = new CkSocket();
// Connect to the server using TLS.
var bTls = true;
var maxWaitMs = 5000;
success = socket.Connect("example.com",5000,bTls,maxWaitMs);
if (success == false) {
console.log(socket.LastErrorText);
return;
}
// Read a four-byte length prefix as a signed 32-bit integer (network byte order by default). A
// return value of -1 indicates failure.
var messageLength = socket.ReceiveCount();
if (messageLength < 0) {
console.log(socket.LastErrorText);
return;
}
console.log("The peer will send " + messageLength + " bytes.");