Tag Archive for 'C#'

I Am Not A Programmer Of C# Sockets

It has come to my attention that there are people out there that are not programmers, well it’s okay we can’t all be perfect now can we? Recently I have been working on a class in sockets programming using the .NET framework and Visual Studio 9.

Well there isn’t too much that I can say good about sockets but at the same time there isn’t too much bad either. C# really isn’t all that hard to program with in the first place so getting a socket all set up and connected isn’t really all that hard. Go ahead and take a quick little look at the example code below and you will see what I mean.
byte[] codedMsg = new byte[32];//create new byte array
Socket sock = null;//create a new socket variable
//create a new socket
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//create a server address endpoint to send data
IPEndPoint serverEndpoint = new IPEndPoint(Dns.Resolve(hostName).AddressList[0], portNum);
sock.Connect(serverEndpoint);//connect socket to server
//encode message in ASCII to send
codedMsg = Encoding.ASCII.GetBytes(sendData);
//send byte array data to server
sock.Send(codedMsg, codedMsg.Length, SocketFlags.None);

With the above example you can see how the socket needs to be created to be used, a connection must be made and the data must be formatted properly so it is understood by the other end. All in all it really isn’t that hard to use a blocking connection and just to create a byte array from a string. Other than that you will be certain to have some extra fun tyring to figure out how to do other things.