Friday, November 2, 2007

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.


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace NetworkStreamSocketClient
{
class Program
{
static void Main(string[] args)
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSocket.Connect(ipEnd);

string strData = "Message from client end.";
byte[] clientData = new byte[1024];
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.
ns.Flush();

byte[] serverData = new byte[1024];
//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
ns.Close();
clientSocket.Close();
Console.ReadLine();
}
}
}


3 comments:

Huu Nhan said...

I have problem, i write program send file : clientA -file-> server -file-> clientB. I send file from clientA to server successfull, but i can't send file from server -> clientB, with error "non-socket"....
I think, server unknown port on clientB, althrough I save client connection information in array.

Chua said...

I would like to ask, you said you used synchronous sockets for asynchronous transfer. How to use these synchronous sockets for synchronous transfer? Thank you!

andre_fsk said...

Thank you! Very good example!