Master C# Logo banner
Welcome to MasterCSharp.com - Master C#, the easy way... - by Saurabh Nandu

 


TCP Date Time Client/Server v2

Add Comment
 

 
Download File SDK
tcpdatev2.zip (9kb) Beta2

Introduction
This applications shows the implementation of "System.Net.Sockets" namespace. In this example you will learn how to use the "TcpListener" and "TcpClient" classes from the "System.Net.Sockets" namespace.
    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.
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.
Once connected it receives the current Date Time from the server and then disconnects from the server. The code of this example has been updated for .NET SDK beta2.

Changes from beta1 to beta2

.NET SDK beta1 .NET SDK beta2
TCPListener class TcpListener class
TCPClient class TcpClient class
TCPListener.Accept method TcpListener.AcceptSocket or
TcpListener.AcceptClient method
String.ToChar method has been removed -

Requirements
1) .NET SDK beta2 (Note: This code might not run on future versions of the SDK).
2) This example will dot run under firewalls.

Execution
1) Run the DateServer.exe first to start the server .(The server by default listens for connection on port 4554).
2) Run the DateClient.exe which will connect to the server and get the current date time from it.

Code:
1) DateServer.cs :- The Date Time Server

namespace SaurabhNet {
 using System;
 using System.Net.Sockets;
 using System.Net ;
 using System.Threading ;
 //Import the necessary Namespaces

 //Class which shows the implementation of the TCP DateTime server

 public class DateServer
 {
   private TcpListener myListener ;
   private int port = 4554 ;
   //The constructor which make the TcpListener start listening on the
   //given port.
   //It also calls a Thread on the method StartListen(). 

   public DateServer()
   {
     try{
      //start listing on the given port
      myListener = new TcpListener(port) ;
      myListener.Start();
      Console.WriteLine("Server Ready -Listening for new Connections ");
      //start the thread which calls the method 'StartListen'
      Thread th = new Thread(new ThreadStart(StartListen));
      th.Start() ;

     }
     catch(Exception e)
     {
       Console.WriteLine("An Exception Occurred while Listening :"
              +e.ToString());
      }
    }

    //main entry point of the class
    public static void Main(String[] argv)
    {
      DateServer dts = new DateServer();
    }

    //This method Accepts new connection and
    //First it receives the welcome massage from the client,
    //Then it sends the Current date time to the Client.
    public void StartListen()
    {
      while(true)
      {
	//Accept a new connection
	Socket mySocket = myListener.AcceptSocket() ;
	if(mySocket.Connected)
	{
	  Console.WriteLine("Client Connected!!") ;
	  //make a byte array and receive data from the client 
	  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)) ;
	  //get the current date/time and convert it to string
	  DateTime now = DateTime.Now;
	  String strDateLine ="Server: The Date/Time Now is: "
                  + now.ToShortDateString()
		+ " " + now.ToShortTimeString();
	  // Convert to byte array and send
	  Byte[] byteDateLine=
             Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
	  mySocket.Send(byteDateLine,byteDateLine.Length,0);
	}
      }
    }
  }
}	

 

2) DateClient.cs:- The Date Time Client

namespace SaurabhNet {
  using System ;
  using System.Net.Sockets ;
  using System.Net ;
  using System.Threading ;

  //Class which shows the implementation of the TCP DateTime Client
  public class DateClient
  {
    //the needed member fields
    private TcpClient tcpc;
    private string name ;
    private int port=4554 ;
    private bool readData=false ;

    //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
    public DateClient(string name)
    {
      //a label
      tryagain :
      this.name=name ;
      try
      {
	//connect to the "localhost" at the give port
	//if you have some other server name then you can use that
	//instead of "localhost"
	tcpc =new TcpClient("localhost",port) ;
	//get a Network stream from the server
	NetworkStream nts = tcpc.GetStream() ;
	//if the stream is write-able then write to the server
	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) ;
	  //flush to stream 
	  nts.Flush() ;
	}
	//make a loop to wait until some data is read from the stream
	while(!readData&&nts.CanRead)
	{
	  //if data available then read from the stream
	  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)) ;
	    //Exit the loop  
	    readData=true ;
	   }
	}
      }
      catch(Exception e)
      {
	Console.WriteLine("Could not Connect to server because "+
             e.ToString());
	//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
	Console.Write("Do you want to try Again? [y/n]: ") ;
	string check = Console.ReadLine();
	if(check[0]=='y'|| check[0]=='Y')
	goto tryagain ;
      }
    }

    //Main Entry point of the client class
    public static void Main(string[] argv)
    {
      //check to see if the user has entered his name
      //if not ask him if he wants to enter his name.
      if(argv.Length<=0)
      {
	Console.WriteLine("Usage: DataClient <yourname>") ;
	Console.Write("Would You like to enter your name now [y/n] ?") ;
	string check = Console.ReadLine();
	if(check[0]=='y'|| check[0]=='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() ;
      }
    }
  }
}

Comments

Add Comment
 

Copyright 2011 MasterCSharp.com. All rights reserved.