Client Socket Programming using C#.Net for Beginner

Now starts for Client part of socket application.

Now I will show a simple client socket with an example:

You have to follow just few steps these are:

I. Create a Ip address object with Server Ip using Dns.

IPAddress []ipAddress= Dns.GetHostAddresses("localhost");

II. Again built an IPEndPoint with that IPAddress with same port of server.

IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);

III. Now creates a socket object with three parameter like code.

Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);

IV. Now create a byte array to send data to server.

V. Finally send that byte array to server.

clientSock.Send(clientData);

VI. To receive data from server just wait socket using Receive function, when some data received by client socket then it fill a byte array and return a interger value received bytes length.

int len = clientSock.Receive(serverData);

VII. Now close the client socket.

The complete client code is giving below:

using System;

using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Client_Socket
{
class Program
{
static void Main(string[] args)
{
IPAddress []ipAddress= Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSock.Connect(ipEnd);

string strData = "Message from client end.";
byte[] clientData = new byte[1024];
clientData = Encoding.ASCII.GetBytes(strData);
clientSock.Send(clientData);

byte[] serverData = new byte[1024];
int len = clientSock.Receive(serverData);
Console.WriteLine(Encoding.ASCII.GetString(serverData,0,len));
clientSock.Close();

Console.ReadLine();

}
}
}