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);
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