Socket Programming in C# .Net

Dot Net Programming in C# with source code and DLL file. Covers Socket, Remoting, Stored Procedure, ASP.Net, IO, Web Service, Windows Service, Installer, Console Programming, Win Forms, Web Forms, Ajax, Web publishing, Text Chat, Large File Transfer, File Handling etc.

Download source code from here

Client Socket 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();

}
}
}
All C# blogs

Labels: , , , , , ,

Client Socket 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();

}
}
}
All C# blogs

Labels: , , , , , ,

  1. Blogger asif | November 5, 2008 12:30 AM |  

    Dear frined, I want to send the data from client to server through socket using Asp.net page, please provide me code.
    thanks.
    asif

  2. Blogger naveen | July 26, 2009 5:13 AM |  

    i work for a mnc level5 company as a software engineer in .net technologies.
    We use a third party component to transfer the files @ rate of greater than @20 MB size.
    I have got an idea to replace that component as we are facing many issues with that.So my requirement is i want to build a component susch that it should be a platform independent and it should be able to transfer the files across the organizations.As i believe it could be done using the Socket programming i just want to know the time it takes to transfer the files.i am much worried about it.Let me know anyone could have handled such type of scenarios.

leave a response

Socket Programming in C# .Net

Dot Net Programming in C# with source code and DLL file. Covers Socket, Remoting, Stored Procedure, ASP.Net, IO, Web Service, Windows Service, Installer, Console Programming, Win Forms, Web Forms, Ajax, Web publishing, Text Chat, Large File Transfer, File Handling etc.

Download source code from here

Server Socket for beginner

For beginner socket is quite complicated. But it's not very hard to learn. Basically I've learned it within few hours. So I believe it can learn any body. However let's start.

Socket programming have two part
I. Server
II. Client.

I. Server:
To start server need to follow some steps, these are:
i. First create a IPEndPoint
[e.g. IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port);]

ii. Create a socket object.
[Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);]

iii. Bind socket with IPEndPoint.
[sock.Bind(ipEnd);]

iv. Place socket in Listen mode (to accept call of client)
[sock.Listen(maxClientReceived);]

v. When any call comes from client Accept that call.
[Socket clientSock = sock.Accept();]
At that position Accept() return a new socket to continue communication with called client. By that socket Client-Server communication continue.

To send some data (in byte array form) to client from server just write
clientSock.send(byteArrayData);

To receive client data just write
int receivedLen= clientSock.Receive(clientData);
Receive() function reads data in byte array form from client socket and writes to 'clientData' array, and return integer value how much bytes has received.

I'm giving complete code of a simple server socket below:-


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace beginSocketServer
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024];
int receivedBytesLen = clientSock.Receive(clientData);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
Console.WriteLine("Received Data {0}", clientDataInString);
string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData= Encoding.ASCII.GetBytes(clientStr);
clientSock.Send(sendData);
clientSock.Close();
Console.ReadLine();
}
}
}


To run that server code you don't need to write client code just open a webbrowser and write (I've use Mozilla Firefox 2.0.0.7) :
http://localhost:5656/

Server console output was:

Received Data GET / HTTP/1.1Host: localhost:5656User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,
*/*;q=0.5Accept-Language: en-us,en;q=0.5Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-alive

And in web browser output was:
Client Data Received.

Ok, Simple server socket application has done. Next will give simple client socket application for beginner.


see more

Labels: , , , , , , ,

Server Socket for beginner

For beginner socket is quite complicated. But it's not very hard to learn. Basically I've learned it within few hours. So I believe it can learn any body. However let's start.

Socket programming have two part
I. Server
II. Client.

I. Server:
To start server need to follow some steps, these are:
i. First create a IPEndPoint
[e.g. IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port);]

ii. Create a socket object.
[Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);]

iii. Bind socket with IPEndPoint.
[sock.Bind(ipEnd);]

iv. Place socket in Listen mode (to accept call of client)
[sock.Listen(maxClientReceived);]

v. When any call comes from client Accept that call.
[Socket clientSock = sock.Accept();]
At that position Accept() return a new socket to continue communication with called client. By that socket Client-Server communication continue.

To send some data (in byte array form) to client from server just write
clientSock.send(byteArrayData);

To receive client data just write
int receivedLen= clientSock.Receive(clientData);
Receive() function reads data in byte array form from client socket and writes to 'clientData' array, and return integer value how much bytes has received.

I'm giving complete code of a simple server socket below:-


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace beginSocketServer
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024];
int receivedBytesLen = clientSock.Receive(clientData);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
Console.WriteLine("Received Data {0}", clientDataInString);
string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData= Encoding.ASCII.GetBytes(clientStr);
clientSock.Send(sendData);
clientSock.Close();
Console.ReadLine();
}
}
}


To run that server code you don't need to write client code just open a webbrowser and write (I've use Mozilla Firefox 2.0.0.7) :
http://localhost:5656/

Server console output was:

Received Data GET / HTTP/1.1Host: localhost:5656User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,
*/*;q=0.5Accept-Language: en-us,en;q=0.5Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-alive

And in web browser output was:
Client Data Received.

Ok, Simple server socket application has done. Next will give simple client socket application for beginner.


see more

Labels: , , , , , , ,

  1. Blogger Sumanta Pramanick | October 4, 2007 6:37 AM |  

    Nice and Help full information, please provide something more details.

  2. Blogger joshy | October 29, 2007 10:24 AM |  

    Hi While went through caught this blogs...however great effort...

    Joshy
    kuwait

  3. Blogger joshy | October 29, 2007 11:15 AM |  

    hi if u dont mind , pls tell me how i can compile above program . Do i need to create class library types or Console Application type.
    if the case first how i will compile ? thanks.

    Joshy

  4. Blogger Suman Biswas | October 29, 2007 11:26 AM |  

    Hi Joshy,
    Thanks for your reply. These codes are completely ready made. You just create a console application then remove all codes from there and just copy and paste all code (any of article), then built and run or directly run it.
    Hope your requirement will be solved.
    Thanks again, please reply about your experiance.
    Suman Biswas, India

  5. Blogger Jagadish Manna | November 1, 2007 1:43 AM |  

    This is actually good artical. I think it will be helpful to all particularly who are working on soket programming. I need more artical like these.I wise him best of luck.
    Jaga

  6. Blogger bodat | November 11, 2007 5:17 PM |  

    hi tanks for this!!!
    any sample code on voice chat and file transfer?? thanks in advance!!

  7. Blogger bodat | November 11, 2007 5:18 PM |  

    hi tanks for this!!!
    any sample code on voice chat and file transfer?? thanks in advance!!

  8. Blogger Suman Biswas | November 11, 2007 9:38 PM |  

    Hi Bodat,
    Thanks for reading my blog.
    Very soon I will post new article on File Transfer, please visit my blog in future. And now I'm working on voice chat by C# socket, but still it's not in such stage by that I can write article for audience. In future it will be.
    Thanks again,
    Suman

  9. Blogger bodat | November 12, 2007 3:29 AM |  

    thanks in advance!!!
    i have found and enhance code in
    java for voice chat!!! but i cannot
    find one in c#!! please email me if
    you have completed it, thanks!!

  10. Blogger Weng | December 13, 2007 6:55 PM |  

    This is very good article but is good if you can provide this server listen to more than one browser...

    Good Jobs.

  11. Blogger SHINOJ | June 6, 2008 9:58 AM |  

    hi if u don't mind,pls tell me how to transfer file client to client through server using sockets

  12. Blogger Suman Biswas | June 6, 2008 10:10 AM |  

    Hi,
    To transfer data need to connect server-client socket. Now if your client ip can resolved directly ( both side ip can get directly) then you just connect and send data. But if you can't connect directly then problem comes. Generally it happens in internet based application but for lan type communication it can connect easyly. So for internet based application need to help of one dadecated ip. Which will act as Server. So to send data you need to send Sender client->server->Receiver client.
    Hope it will help you.

  13. Blogger Vijay | September 11, 2008 3:07 AM |  

    Hi.,
    Have u done any multi client chat application using c#..? i.e one to many chat application..If yes pls send it to my mail..

    ji_vijay@yahoo.co.in

    Thanx in advance..

  14. Blogger Suman Biswas | September 11, 2008 4:55 AM |  

    Hi Vijay,
    I've done it. But was using .Net Remoting technology in C#. But I'm sorry because I don't have these code. If you need technical help I can help you. You can search it in codeproject.com.
    Thanks,
    Suman

  15. Blogger Sudheendra | October 17, 2008 12:38 AM |  

    hi,
    Nice code this help me lot.

    Thanks
    sudheendra

  16. Blogger subramani | October 20, 2008 7:30 AM |  

    hi...i just tried ur socket program...i hve some error in my compilation....i dont know how to clear that... i wrote here the following Program..But i got some Errors..can u help me...(subramanitnj@gmail.com)

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

    namespace SocketConsole
    {
    class Program
    {
    static void Main(string[] args)
    {
    PEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    sock.Bind(ipEnd);
    sock.Listen(100);
    Socket clientSock = sock.Accept();
    byte[] clientData = new byte[1024];
    int receivedBytesLen = clientSock.Receive(clientData);
    string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
    Console.WriteLine("Received Data {0}", clientDataInString);
    string clientStr = "Client Data Received";
    byte[] sendData = new byte[1024];
    sendData = Encoding.ASCII.GetBytes(clientStr);
    clientSock.Send(sendData);
    clientSock.Close();
    Console.ReadLine();
    }
    }
    }


    Error List:
    Error 1 The type or namespace name 'PEndPoint' could not be found (are you missing a using directive or an assembly reference?)
    Error 2 The best overloaded method match for 'System.Net.Sockets.Socket.Bind(System.Net.EndPoint)' has some invalid arguments
    Error 3 Argument '1': cannot convert from 'PEndPoint' to 'System.Net.EndPoint' E:\SocketConsole\SocketConsole\Program.cs 15 23 SocketConsole

  17. Anonymous Anonymous | April 18, 2009 6:59 AM |  

    hi...bro please can u tell me.
    how you hyperlinked your content.
    plz mail me at manjeetkumar53@gmail.com

leave a response