Sockets in .Net
nate said:
normally I add a winsock control to my form set it to listen then use it to transmit data from one program to the other. This code looks like I dont need to add the control to the form, is this correct?
A socket is not generally something that is part of, or supports, a user interface. It is therefore counterintuitive to have a UI socket control, and in .Net there isnt one. The
System.Net and
System.Net.Sockets namespaces contain classes for implementing sockets, such as the
TcpListener mentioned above.
Socket event handling differs much from VB6 and below. The above code starts a listening socket and then serves off each incoming request to a new
Socket object. There is also an
AcceptTcpClient method which returns the new connection as a
TcpClient. The TcpClient class is a simplified wrapper for a Socket, and exposes a
NetworkStream which can be used to send and receive via the synchronous (blocking)
Read and
Write methods or the asynchronous (non-blocking)
BeginRead/
EndRead and
BeginWrite/
EndWrite methods. The Socket class also contains these methods if you prefer to work with Sockets (as I do).
When a
Socket or
TcpClient is returned from
AcceptSocket or
AcceptTcpClient you probably want to begin receiving data asycnhronously. To do this you need to call
BeginRead, specifying the callback method (delegate) to be invoked when the receive operation has completed - ie when there is data to process. In the delegate method you invoke
EndReceive and process the data accordingly, before calling
BeginReceive again to continue receiving.
Im sure there are examples in the forum if you search for them, otherwise I can write one quickly.
Good luck