Question:
I’m in the process of writing an application using VB6 implementing the Socket object via ActiveX using WithEvents and hope you can point me in the right direction.
First up is whether there’s an event on a socket that has been created from a listening socket using AcceptNextConnectionAsync, which fires when a client disconnects. At the moment I’m polling the sockets but if there’s a way to get that via an event that would seem to be more efficient. Looking at the documentation it says that KeepAlive is enabled by default, so would this indicate that there is some mechanism within the Socket already to determine if the connection is closed and so fire an event? If there isn’t already an event to do this, could it be considered for a future version?
The other issue I’m having is that I’m trying to build both server and client applications using sockets, and using async methods as neither side can be blocking. I’m occassionally getting crashes – oddly not in the VB6 IDE but in the compiled applications. I’m making sure I’m not doing any UI updates in the async code and am instead setting properties on classes that are shared between the UI and the socket handling code. The examples that you have available for VB6 on example-code.com are all based on a single chunk of code that is run sequentially, do you have any examples that show how to use event driven asynchronous calls in VB6?
The short answer is that because async methods run in a background thread, it's not possible for them to make a callback into VB6 code because it's from the background thread, and because of the architecture of COM/ActiveX + VB6. It may be possible in other COM/ActiveX environments (which remains to be seen), so the TaskCompleted method exists, but it can never be used in VB6. Therefore, the only solution is to setup a timer event that periodically checks for task completion. This is demonstrated in this project here on GitHub -- https://github.com/chilkatsoft/VB6-Accept-Connection-Async
Here are some drawings to understand a synchronous and asynchronous calls better:
A Synchronous Method Call w/ Callback
A VB6 program is event driven. When it begins, there is a main UI thread that runs an event loop, which is not your application code. When something happens, it makes a call to a subroutine or function in your VB6 app. I'll walk through the steps in a synchronous method call with a callback:
An Asychronous Method Call
Here's what happens in an asynchronous method call: