Question:
There are no examples for asynchronous sockets receiving byte data. I can't tell how to identify when such a call has completed.
Within the socket documentation there is a AsyncReceiveBytesN method, but the only way to know how many bytes to pass is to know what the server is sending. For my synchronous calls thus far I have used ReceiveCount easily enough.
/*
* Here we send and receive in one blocking call
*/
public function sendMessage(message : String) : String {
inUse = true;
var byteCount : int;
init();
Response = {};
ResponseStr = '{}';
if (!Connected())
return ResponseStr;
if (Transmit(message)) {
byteCount = socket.ReceiveCount()
if (byteCount>0) {
ResponseStr = socket.ReceiveBytesN(byteCount);
try {
Response = parse(ResponseStr);
}
catch (e) {
log(socket.LastErrorText)
}
}
}
lastRecieved = {asString : ResponseStr , asObject : Response}
inUse = false;
return ResponseStr;
}
But with an asynchronous receive, how do I call ReceiveCount without blocking the thread? And when can I call it? It obviously won't be ready when initiating the asynchronous process, but the the process is initiated by socket.AsyncReceiveBytesN()
/*
* our outgoing message is relatively small, so we will send
* that here, the asynch begins on the check for response
*/
public function Asynch_sendMessage(message : String) : Boolean { // synchronous
inUse = true;
init();
Response = {};
ResponseStr = '{}';
if (!Connected())
return false;
if (Transmit(message)) {
socket.AsyncReceiveBytesN( ?? ); // I want to allow for receiving N bytes, but the server
// hasn't processed my request yet, how to I tell the
return true; // component how many bytes we are looking for??
}
inUse = false;
socket.Close();
return false;
}
public function Asynch_checkMessage() : String { // asynchronous
/*
* basically: check for the message receive to complete
* and if has, return our information encoded as a string.
*/
if (socket.AsyncReceiveFinished === 1)
if (socket.AsyncReceiveSuccess === 1) {
ResponseStr = decode(socket.AsyncReceivedBytes);
try {
Response = parse(ResponseStr);
}
catch (e) {
log(socket.LastErrorText);
}
lastRecieved = {asString : ResponseStr , asObject : Response};
}
inUse = false;
socket.Close();
return ResponseStr;
}
inUse = true;
return 'Not Ready';
}
It seems to me that socket.AsyncReceiveBytesN() cannot be used with a non-constant value for N, but in my server the data is compressed before sending, and therefor the length is not known in advance.
All I can think to do is have the asynchronous method call a different function on the server that will send a string instead that is marked with "-EOM-", but that would counter my efforts to reduce the size with compression...
Yes, you could send the byte count in a string. To minimize the size of the string, you could use hex representation of the number, and with the end marked by a single char, such as "." that cannot possibly be a hex digit. For example, to send 500, you would send "1F4."