Synchronous Client 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 Client socket with Network stream in C# .Net has written and in different blog post contains the Server 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.
static void Main(string args)
IPAddress ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress, 5656);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string strData = "Message from client end.";
byte clientData = new byte;
clientData = Encoding.ASCII.GetBytes(strData);
//Difference is here only, use of Network Stream class.
//Just create a object of Network Stream class with your estublished socket, then use it.
NetworkStream ns = new NetworkStream(clientSocket);
//Write function writes all bytes to send receiver end of connected socket.
ns.Write(clientData, 0, clientData.Length);
//Flush() use to clear all data from Stream object to future use.
byte serverData = new byte;
//Now stream object wait for receive response from other end.
int length = ns.Read(serverData, 0, serverData.Length);
Console.WriteLine(Encoding.ASCII.GetString(serverData, 0, length));
//Communication completed, now free all resource