Thursday, November 8, 2007

Synchronous Server Socket using Network Stream in C# .Net Programming

Hi frends,I’m back again with two sample socket application. These two project also for beginner’s in C#.Net Socket world. One of these is Server socket application and another is Client socket application. Both application has used NetworkStream class to send and receive data between Client and Server. These two has written based on previous articles on Socket programming and these are very easy to learn. I hope any one can understood these very easyly. If you feel any problem then please reply me via comment I will response these.

Here Server socket with Network stream in C# has written and in different blog post contains the client application. Both two has written based on synchronous communication mode, but in future I will show you, how you can built asynchronous socket application by these synchronous socket. So lets starts code.


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

namespace NetworkStreamSocketServer
{
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];

//With other Socket server application difference only here.
//Create an Network stream object and wait for client's request
NetworkStream ns = new NetworkStream(clientSock);

//Wait for new connection and to receive data from client
int receivedBytesLen = ns.Read(clientData, 0, clientData.Length);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
ns.Flush();//Free Stream buffer
Console.WriteLine("Received Data {0}", clientDataInString);

string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData = Encoding.ASCII.GetBytes(clientStr);
//Now network stream object send some data to client
ns.Write(sendData, 0, sendData.Length);
//Release all resources
ns.Close();
clientSock.Close();
Console.ReadLine();
}
}
}

4 comments:

SHINOJ said...

How to send files client to client through server?

Ravi said...

hi,

i have developed Async Server using socket class. but it giving me 15 TPS. do u have any idea for high performance server.

mcamail2002@gmail.com

Suman Biswas said...

Hi Ravi,
I can't understand about 15TPS (TPS?). So please enplane quite more clearly.


Thanks,
Suman

Ravi said...

thanks for reply.Acually i,m talking about Txn Per Second (TPS). my server giving 15 TPS but want more than 15 TPS. that's why i am looking high perfomance Socket server or Multi threaded server.

Thanks
Ravi