TCP Date Time Client/Server
Add Comment<div align="center"> <table border="0" width="70%" class="outline"> <tr> <td width="50%" class="outline"><b>Download File</b></td> <td width="50%" class="outline"><b>SDK</b></td> </tr> <tr> <td width="50%" class="outline"><a href="../../file/tcpdate.zip" class="wbox">tcpdate.zip</a> (9kb)</td> <td width="50%" class="outline">Beta1</td> </tr> </table> </div> <p> <span class=wboxheado>Introduction</span><br> This applications shows the implementation of "System.Net.Sockets" namespace. In this example we will learn how to use the "TCPListener" and "TCPClient" classes from the "System.Net.Sockets" namespace.<br> This example consists of two files. The "DateServer" class which uses the "TCPListener" class to accept requests from new clients. Once the client is connected with the server, the server will send it the the Current Date and Time and then disconnect it, and listen for more clients.<br> The "DateClient" class uses the "TCPClient" class. It connects to the server on the specified port and send the clients name to the server upon connection.<br> Once connected it receives the current Date Time from the server and then disconnects from the server.</p> <p><span class=wboxheado>Requirements</span><br> 1) .NET SDK beta1 (Note: This code might not run on future versions of the SDK).<br> 2) This example will not run behind firewalls.<br> <br> <span class=wboxheado>Execution</span><br> 1) Run the DateServer.exe first to start the server .(The server by default listens for connection on port 4554).<br> 2) Run the DateClient.exe which will connect to the server and get the current date time from it.</p> <p><span class=wboxheado>Code:</span><br> 1) <i><b>DateServer.cs</b> :- The Date Time Server</i></p> <table border="0" width="100%" class="code" cellspacing="0" cellpadding="0"> <tr> <td width="100%"> <pre>namespace SaurabhNet { using System; using System.Net.Sockets; using System.Net ; using System.Threading ; <span class=cmt>//Import the necessary Namespaces</span> <span class=cmt>//Class which shows the implementation of the TCP Date server</span> public class DateServer { private TCPListener myListener ; private int port = 4554 ; <span class=cmt>//The constructor which make the TCPListener start listening on the //given port. //It also calls a Thread on the method StartListen(). <SEE cref="StartListen" /> </span> public DateServer() { try{ <span class=cmt>//start listing on the given port</span> myListener = new TCPListener(port) ; myListener.Start(); Console.WriteLine("Server Ready -Listining for new Connections "); <span class=cmt>//start the thread which calls the method 'StartListen'</span> Thread th = new Thread(new ThreadStart(StartListen)); th.Start() ; } catch(Exception e) { Console.WriteLine("An Exception Occurred while Listing :" +e.ToString()); } } <span class=cmt>//main entry point of the class</span> public static void Main(String[] argv) { DateServer dts = new DateServer(); } <span class=cmt>//This method Accepts new connection and //First it receives the welcome massage from the client, //Then it sends the Current time to the Client.</span> public void StartListen() { while(true) { <span class=cmt>//Accept a new connection</span> Socket mySocket = myListener.Accept() ; if(mySocket.Connected) { Console.WriteLine("Client Connected!!") ; <span class=cmt>//make a byte array and receive data from the client </span> Byte[] receive = new Byte[64] ; int i=mySocket.Receive(receive,receive.Length,0) ; char[] unwanted = {' ',' ',' '}; string rece = System.Text.Encoding.ASCII.GetString(receive); Console.WriteLine(rece.TrimEnd(unwanted)) ; <span class=cmt>//get the current date/time and convert it to string</span> DateTime now = DateTime.Now; String strDateLine ="Server: The Date/Time Now is: " + now.ToShortDateString() + " " + now.ToShortTimeString(); <span class=cmt>// Convert to byte array and send</span> Byte[] byteDateLine= Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray()); mySocket.Send(byteDateLine,byteDateLine.Length,0); } } } } } </pre> </td> </tr> </table> <P> </P> <P>2)<I><b> DateClient.cs</b>:- The Date Time Client</I></P> <FONT size=2> <table border="0" width="100%" class="code" cellspacing="0" cellpadding="0"> <tr> <td width="100%"> <pre>namespace SaurabhNet { using System ; using System.Net.Sockets ; using System.Net ; using System.Threading ; <span class=cmt>//Class which shows the implementation of the TCP Date Client</span> public class DateClient { <span class=cmt>//the needed member fields</span> private TCPClient tcpc; private string name ; private int port=4554 ; private bool readData=false ; <span class=cmt>//Constructor which contains all the code for the client. //It connects to the server and sends the clients name, //Then it waits and receives the date from the server</span> public DateClient(string name) { <span class=cmt>//a label</span> tryagain : this.name=name ; try { <span class=cmt>//connect to the "localhost" at the give port //if you have some other server name then you can use that //instead of "localhost"</span> tcpc =new TCPClient("localhost",port) ; <span class=cmt>//get a Network stream from the server</span> NetworkStream nts = tcpc.GetStream() ; <span class=cmt>//if the stream is writiable then write to the server</span> if(nts.CanWrite) { string sender = "Hi Server I am "+name ; Byte[] sends = System.Text.Encoding.ASCII.GetBytes(sender.ToCharArray()); nts.Write(sends,0,sends.Length) ; <span class=cmt>//flush to stream </span> nts.Flush() ; } <span class=cmt>//make a loop to wait until some data is read from the stream</span> while(!readData&&nts.CanRead) { <span class=cmt>//if data available then read from the stream</span> if(nts.DataAvailable) { byte[] rcd = new byte[128]; int i=nts.Read( rcd,0,128); string ree = System.Text.Encoding.ASCII.GetString(rcd); char[] unwanted = {' ',' ',' '}; Console.WriteLine(ree.TrimEnd(unwanted)) ; <span class=cmt>//Exit the loop </span> readData=true ; } } } catch(Exception e) { Console.WriteLine("Could not Connect to server because "+ e.ToString()); <span class=cmt>//Here an exception can be cause if the client is started before //starting the server. //A good way to handle such exceptions and give the client //a chance to re-try to connect to the server</span> Console.Write("Do you want to try Again? [y/n]: ") ; char check = Console.ReadLine().ToChar(); if(check=='y'|| check=='Y') goto tryagain ; } } <span class=cmt>//Main Entry point of the client class</span> public static void Main(string[] argv) { <span class=cmt>//check to see if the user has entered his name //if not ask him if he wants to enter his name.</span> if(argv.Length<=0) { Console.WriteLine("Usage: DataClient <yourname>") ; Console.Write("Would You like to enter your name now [y/n] ?") ; char check = Console.ReadLine().ToChar(); if(check=='y'|| check=='Y') { Console.Write("Please enter you name :") ; string newname=Console.ReadLine(); DateClient dc = new DateClient(newname) ; Console.WriteLine("Disconnected!!") ; Console.ReadLine() ; } } else { DateClient dc = new DateClient(argv[0]) ; Console.WriteLine("Disconnected!!") ; Console.ReadLine() ; } } } }</pre> </td> </tr> </table>