-
Notifications
You must be signed in to change notification settings - Fork 1
Description
As demonstrated elsewhere (#2 (comment)) there are issues. Here's a discussion starter for improvement:
How Can It Be Instead?
I think the fact that you are dealing with global state causes 90% of your problems.
Next up, you could probably stop pretending to do asynchronous operations. That removes all the timing windows. Of course, you might still want to receive messages event-driven - which probably fits the use-case well. However, if so, then disconnecting (now a synchronous operation) should cancel all reads, so you wouldn't get ON_DATA events afterwards.
You'd allow multiple sessions, with their own callbacks, so there's no need for confusion between connections (undead or alive). You'd name them connections, as this is what the user thinks of them as. Synopsis sketch (in pseudo code, I don't speak AutoIt)
var ws : handle; // handle can be just int
fun on_data(handle, text) { // sample callback
if (handle == ws) { // in case you have the same handler for many connections
X_send(handle, "Echo reply " + text);
foreach (other : other_connections) {
X_send(other, "Broadcast from ws: " + text);
}
}
};
ws = X_connect("ws://host:789/path", on_data, on_error, on_disconnect); // synchronously connects
if (ws <> INVALID_HANDLE) {
// connection is already receiving and ready to send
X_send(ws, "Hello world");
sleep(10); // during this time messages may be received and the server may disconnect
if (X_isconnected(ws)) {
console.print("Hey, the server had already disconnected");
}
if (X_close(ws)) {
console.print("Hey, the server had not disconnected, we (successfully/ungracefully) closed");
/* if there was a close problem, the connection is still gone but you
* would have gotten `on_error` callback about it
*
* since we did close the connection here, the on_disconnect callback
* fired while X_close() was performed
*/
}
else {
/* connection had already been closed. the on_disconnect callback fired before X_close() was invoked */
}
}
Note how on_connect_cb is redundant now. Note also how you can never forget to unwire callbacks.
The callbacks might not need the handle argument if you can make closures in AutoIt script.
Originally posted by @sehe in #2 (comment)