TCP/IP ECHO SERVER

Building a echo server and a client in same PC

Page 1 of 1

0 Replies - 11969 Views - Last Post: 06 July 2008 - 05:21 PM Rate Topic: -----

#1 jee  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 10
  • Joined: 20-April 08

TCP/IP ECHO SERVER

Post icon  Posted 06 July 2008 - 05:21 PM

Hi exp's here i have a criteria which i was having some dilemma regarding the code and its structures in visual studio 2008..

Here my application is about creating a TCP/IP server which receives every message from a client and replies the same message to the client.. So i mentioned TCP ECHO SERVER...

Here i have the code for the TCP Server and the echo server which i got from some articles and tutorials..



This Code is for the server.....

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Collections;

namespace TcpLib
{
  public class ConnectionState
  {
	internal Socket _conn;
	internal TcpServer _server;
	internal TcpServiceProvider _provider;
	internal byte[] _buffer;
   public EndPoint RemoteEndPoint
	{
	  get{ return _conn.RemoteEndPoint; }
	}

	public int AvailableData
	{
	  get{ return _conn.Available; }
	}

	public bool Connected
	{
	  get{ return _conn.Connected; }
	}

	public int Read(byte[] buffer, int offset, int count)
	{
	  try
	  {
		if(_conn.Available > 0)
		  return _conn.Receive(buffer, offset, count, SocketFlags.None);
		else return 0;
	  }
	  catch
	  {
		return 0;
	  }
	}
public bool Write(byte[] buffer, int offset, int count)
	{
	  try
	  {
		_conn.Send(buffer, offset, count, SocketFlags.None);
		return true;
	  }
	  catch
	  {
		return false;
	  }
	}
	public void EndConnection()
	{
	  if(_conn != null && _conn.Connected)
	  {
		_conn.Shutdown(SocketShutdown.Both);
		_conn.Close();
	  }
	  _server.DropConnection(this);
	}
  }
  public abstract class TcpServiceProvider:ICloneable
  {
	public virtual object Clone()
	{
	  throw new Exception("Derived clases must override Clone method.");
	}
	public abstract void OnAcceptConnection(ConnectionState state);
	public abstract void OnReceiveData(ConnectionState state);
	public abstract void ondropConnection(ConnectionState state);
  }
  public class TcpServer
  {
	private int _port;
	private Socket _listener;
	private TcpServiceProvider _provider;
	private ArrayList _connections;
	private int _maxConnections = 100;

	private AsyncCallback ConnectionReady;
	private WaitCallback AcceptConnection;
	private AsyncCallback ReceivedDataReady;
 
	public TcpServer(TcpServiceProvider provider, int port)
	{
	  _provider = provider;
	  _port = port;
	  _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
		ProtocolType.Tcp);
	  _connections = new ArrayList();
	  ConnectionReady = new AsyncCallback(ConnectionReady_Handler);
	  AcceptConnection = new WaitCallback(AcceptConnection_Handler);
	  ReceivedDataReady = new AsyncCallback(ReceivedDataReady_Handler);
	}
   public bool Start()
	{
	  try
	  {
		_listener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), _port));
		_listener.Listen(100);
		_listener.BeginAccept(ConnectionReady, null);
		return true;
	  }
	  catch
	  {
		return false;
	  }
	}
	private void ConnectionReady_Handler(IAsyncResult ar)
	{
	  lock(this)
	  {
		if(_listener == null) return;
		Socket conn = _listener.EndAccept(ar);
		if(_connections.Count >= _maxConnections)
		{
		  string msg = "SE001: Server busy";
		  conn.Send(Encoding.UTF8.GetBytes(msg), 0, msg.Length, SocketFlags.None);
		  conn.Shutdown(SocketShutdown.Both);
		  conn.Close();
		}
		else
		{
		  ConnectionState st = new ConnectionState();
		  st._conn = conn;
		  st._server = this;
		  st._provider = (TcpServiceProvider) _provider.Clone();
		  st._buffer = new byte[4];
		  _connections.Add(st);
		  ThreadPool.QueueUserWorkItem(AcceptConnection, st);
		}
	   _listener.BeginAccept(ConnectionReady, null);
	  }
	}
	private void AcceptConnection_Handler(object state)
	{
	  ConnectionState st = state as ConnectionState;
	  try{ st._provider.OnAcceptConnection(st); }
	  catch {
	  }
	  if(st._conn.Connected)
		st._conn.BeginReceive(st._buffer, 0, 0, SocketFlags.None,
		  ReceivedDataReady, st);
	}

	private void ReceivedDataReady_Handler(IAsyncResult ar)
	{
	  ConnectionState st = ar.AsyncState as ConnectionState;
	  st._conn.EndReceive(ar);
	  if(st._conn.Available == 0) DropConnection(st); 
	  else
	  {
		try{ st._provider.OnReceiveData(st); }
		  catch {
		  }
		  if(st._conn.Connected)
		  st._conn.BeginReceive(st._buffer, 0, 0, SocketFlags.None,
			ReceivedDataReady, st);
	  }
	}


	public void Stop()
	{
	  lock(this)
	  {
		_listener.Close();
		_listener = null;
		foreach(object obj in _connections)
		{
		  ConnectionState st = obj as ConnectionState;
		  try{ st._provider.ondropConnection(st);	}
		  catch{
				 }
		  st._conn.Shutdown(SocketShutdown.Both);
		  st._conn.Close();
		}
		_connections.Clear();
	  }
	}
   internal void DropConnection(ConnectionState st)
	{
	  lock(this)
	  {
		st._conn.Shutdown(SocketShutdown.Both);
		st._conn.Close();
		if(_connections.Contains(st))
			_connections.Remove(st);
	  }
	}


	public int MaxConnections
	{
	  get
	  {
		return _maxConnections;
	  }
	  set
	  {
		_maxConnections = value;
	  }
	}


	public int CurrentConnections
	{
	  get
	  {
		lock(this){ return _connections.Count; }
	  }
	}
  }
}







And this is for the Echo server...


using System;
using System.Text;
using System.Windows.Forms;
using TcpLib;

namespace TcpServer
{
	public class EchoServiceProvider: TcpServiceProvider
	{
		private string _receivedStr;

		public override object Clone()
		{
			return new EchoServiceProvider();
		}

		public override void OnAcceptConnection(ConnectionState state)
		{
		_receivedStr = "";
		if(!state.Write(Encoding.UTF8.GetBytes("Hello World!\r\n"), 0, 14))
		state.EndConnection(); 
		}
		
		public override void OnReceiveData(ConnectionState state)
		{
			byte[] buffer = new byte[1024];
			while(state.AvailableData > 0)
			{
				int readBytes = state.Read(buffer, 0, 1024);
				if(readBytes > 0)
	{
	_receivedStr += Encoding.UTF8.GetString(buffer, 0, readBytes);
				if(_receivedStr.IndexOf("<EOF>") >= 0)
					{
						state.Write(Encoding.UTF8.GetBytes(_receivedStr), 0,
							_receivedStr.Length);
						_receivedStr = "";
					}
				}
				else state.EndConnection(); 
			}
		}


		public override void ondropConnection(ConnectionState state)
		{
		}
	}
}




I have compiled and built it successfully but all i want to check the output of this application of the code...... I want to run both the client and the server in the same system and to check the output, Since i don't know how to perform this task...

I have created a windows form application and wrote the following code for the main form and added two class file to write the above two codes respy...


If anyone knows about this Please help me to come out of this...

NOTE:
For this server i have a form with a command button to close the application and its code as follows....



using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using TcpLib;

namespace TcpServerDemo
{
	public class MainForm: System.Windows.Forms.Form
	{
private System.ComponentModel.Container components = null;

	public MainForm()
		{
			InitializeComponent();
	}
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		[STAThread]
		static void Main() 
		{
			Application.Run(new MainForm());
		}


		private TcpServer Server;
		private System.Windows.Forms.Button btnClose;
		private EchoServiceProvider Provider;
		

	private void MainForm_Load(object sender, System.EventArgs e)
		{
			Provider = new EchoServiceProvider();
			Server = new TcpServer(Provider, 15555);
			Server.Start();
		}


private void btnClose_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

private void MainForm_Closed(object sender, System.EventArgs e)
		{
			Server.Stop();
		}
	}
}





Thanks in advance bro's...
Awaiting for a reply...

This post has been edited by jee: 06 July 2008 - 05:29 PM


Is This A Good Question/Topic? 0
  • +

Page 1 of 1