Monday, 13 August 2012

C# Sockets Programming (Intro to System.Net.Sockets)

Desperate Programmer: I want to write network software and not be bound by weirdo libraries that limit me in how many connections I can make and such like.
Wise Programmer: Then what you need is Sockets. Master sockets and cross the impasse of data transfer across networks.
Adage: Don't trust a Dot Net Programmer to architect an application who has never programmed network software in C# and moreover has never programmed Sockets.
Desperate Programmer: So, then how do I unlock the Sockets functionality of .Net?
Wise Programmer: Start with the System.Net.Sockets namespace and progress from there

Concept Check: What is the Relation between TCP and Sockets?

Socket is a SOFTWARE OBJECT -> that REPRESENTS an endpoint for inter-process communication. Sockets can use various PROTOCOLS (rulesets), such as TCP and UDP.

How do you create a TCP Client in C#? Tell me PRECISELY.

The answer is SIMPLE. You can guess it without knowing C#. Use the TcpClient class. Where does that great TCP client class live? Ans: System.Net.Sockets (part of System.dll).

Suppose your TCP client is aptly named client. To connect the client to a socket, you need to do client.Connect(IPEndPoint). The endpoint consists of an IP address and a port. Now we have a connection. The server has to be up though for this connection to work.

How do you send a message from the Client to the Server?

You need to grab the NetworkStream from the TcpClient.  You can do stuff with the Stream, like write byte arrays to it, and Flush it. To convert a string to a byte array, you can use the class ASCIIEncoding (System.Text, from mscorlib.dll) which represents an encoder. Calling GetBytes on the encoder creates a byte buffer.

How do you create a TCP Server in C#? Again, a precise explanation is requested.
This is just a TcpListener. You create a TcpListener using IPAddress.Any, and the required port.  Calling Start() on the listener starts it listening to incoming requests. The method AcceptTcpClient returns the next TCP client accepted by the listener. Once you have the client object, you can spawn a new thread to handle the client communication.

Writing a TCPClient is child's play. Writing a TCP server is a little more involved.

No comments: