This is the implementation of "System.Net.Sockets". In this example we will learn how to use the "TCPListener" and "TCPClient" classes from the "System.Net.Sockets" namespace.
Download The Code (TCPDate.zip) |
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 Date 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(). |
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 Date 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 writiable 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]: ") ; char check = Console.ReadLine().ToChar(); if(check=='y'|| check=='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 |
No comments:
Post a Comment