Friday, March 11, 2011

.Net Sockets

Hi


If, like me, you come from the Winsock.dll world of VB6 and are trying to find your way around the new System.Net.Sockets and System.Net.Sockets.TcpClient classes, take a look at 


http://www.gnu.org/projects/dotgnu/pnetlib-doc/System/Net/Sockets/Socket.html


Excellent explanation of how to write both a server and client part of an application.

The sample is in C# but is a cinch to adapt to VB.Net.  Am doing that.  When I finish, will put it up in a follow up post.


The basic steps are these




  1. Create a new class that will hold your socket and the data you want to receive/send - the above link calls it the StateObject class
  2. Create an IP address/port combination object called the IPEndPoint
  3. Create a Socket object - an instance of the System.Net.Socket class 
  4. Call BeginConnect method of the Socket object created in Step 3.  This is an asynchronous call.  This call does NOT wait for the connection to be established.  Execution of your application continues immediately after the statement is executed.  The BeginConnect method requires a "callBack" function.  This is a function that will be called when the BeginConnect method finishes.  The finish of the BeginConnect method could mean either a successful or an unsuccesful connection of the socket.  Within the callback function of the BeginConnect method, you should check the "Connected" property of the object.
  5. Within the callback function of the BeginConnect method, start to receive data using the BeginReceive method.  The BeginReceive method is also asynchronous.  You will need a callback function for this as well.
  6. Similarly, you use the BeginSend method asynchronously to send data to a server.  Using a callback function lets your application know the status of each send cycle.  If your application expects the server to acknowledge the data sent, you start a BeginReceive from within the callback of the BeginSend method and the cycle continues.  
Overall, I think the new Socket class is a simpler, much more logical way of handling socket events.  

Very elegant.

Look up the site above.  Very helpful.

Hope this helps




No comments:

Post a Comment