Thursday, September 20, 2007

Server Socket Programming in C#, how to start

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

21 comments:

Sumanta Pramanick said...

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

joshy said...

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

Joshy
kuwait

joshy said...

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

Suman Biswas said...

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

Jagadish Manna said...

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

bodat said...

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

bodat said...

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

Suman Biswas said...

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

bodat said...

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!!

Weng said...

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

Good Jobs.

SHINOJ said...

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

Suman Biswas said...

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.

Vijay said...

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..

Suman Biswas said...

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

Sudheendra said...

hi,
Nice code this help me lot.

Thanks
sudheendra

subramani said...

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

Anonymous said...

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

abhishek said...
This comment has been removed by the author.
abhishek said...

hey man I think U worked really hard to get all these .
well actually i was searching for code to send email in lan to any one but certainly found ur blog abt socket programming and its rocking well done keep it up!!!!!!!!!!!!
hey if u get some time do visit my blog "entity.mywapblog.com". A techno blog hope u will like it.

Jashanpreet said...

bro , little help when i open using your code
static void Main(string[] args)
{
//while (true)
//{
//try
//{
IPEndPoint ipend = new IPEndPoint(IPAddress.Any, 5000);//just like tcplistener , creating what and where to listen
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);//defining socket
soc.Bind(ipend);//binding socket to istener
soc.Listen(100);
Socket sock = soc.Accept();
byte[] welcome = new byte[1024];
welcome = Encoding.ASCII.GetBytes("Welcome to my first server");
sock.Send(welcome);
byte[] recieve = new byte[1024];
// while (!recieve.Equals("x"))
//{
int len = sock.Receive(recieve);
string recieved = Encoding.ASCII.GetString(recieve, 0, len);
Console.WriteLine("Recieved data: {0}", recieved);
byte[] ok = new byte[1024];
ok = Encoding.ASCII.GetBytes("data Recieved");
sock.Send(ok);
//}
sock.Close();
Console.ReadLine();
//}
//catch (Exception e)
//{
// Console.WriteLine(e.ToString());
//}
//}
}
i got an exception on
sock.send(ok);
that
An established connection was aborted by the software in your host machine

can you help and telll me what i did wrong..its a runtime error

Jashanpreet said...

hey it worked with mozilla only