tags:

views:

1524

answers:

4

C# Sockets: How do you handle a socket in C#.NET the way they're handled in VB6 or Delphi (event driven)?

On VB6 or Delphi, when creating a socket, you had an onconnect, onreceive, and onerror events placed into the main code file, how would I replicate the same?

+1  A: 

You should read up on the TcpClient class, network coding isn't nearly as drag and drop as it was in vb6, but you do have a lot more control over the protocol.

Also, there are quite a bit of WinSock clone libraries out there that act and interface about the same as the vb6 equivalent.

Tom Anderson
+2  A: 

You dont have exactly behavior like in VB6/Delphi and you have Async methods and events for doing stuff like it, for example: AsyncTCP Client

Baget
A: 

There is not such a class available in the .Net framework afaik.

It is pretty easy to create a class with OnConnect, OnReceive etc that wraps up the socket class. And if you are unexperienced in making classes that sends events, this is a very good learning experience.

It was the first thing I did when I went from VB6 to .Net and required "winsock".

Wolf5
+1  A: 

The short answer is: By using multithreading techniques.

The long answer is that events are really just a signal that is raised by other code that's continuously checking for a particular set of circumstances. For example a very simple portion of code responsible for raising the DataAvailable event might look like this:

While Socket Is Connected
   If Data Is Available Raise Event DataAvailable
Loop

The .Net library has a Socket class which you can wrap with a class that you design to behave a bit more like the Winsock class that was available in VB6. Once you dig around the documentation for the Socket class and learn how to create custom events for a class it's not difficult to imagine how such a wrapper might be designed. The real hurdle for most developers coming from VB6 (and for me) is that you must learn a bit about multithreaded applications in order for it to work properly.

You can probably find such a wrapper by doing a bit of searching but I would highly encourage you to at least attempt writing your own. With single cored machines quickly becoming a thing of the past experience with multithreading techniques is going to become a requirement of any decent programmer.

Spencer Ruport