Connexion de type tcp/ip

Contenu du snippet

Ca peut vous être utile, surtout pour comprendre le fonctionnement des sockets, et plus particulièrement de la classe TcpClient.

Source / Exemple :


namespace TcpConnection
{
	using System;
	using System.Net;
	using System.Net.Sockets;
	using System.Text;
	using System.IO;

	public class Connection
	{
		public enum State
		{
			Disconnected,
			Connected
		}
		public delegate void DelegToWrite(string Text);

		private State _StateConn;
		private DelegToWrite _OnTextToWrite; 
		private TcpClient _TcpConnect;
		private NetworkStream _Ns;
		private string _HostName;
		private IPAddress _IP;
		private int _Port;
		private string _Sent;
		private string _Received;
		private byte[] _bReceived;
		private int _RecSize;

		public State StateConn
		{
			get{return _StateConn;}
		}

		public DelegToWrite OnTextToWrite
		{
			get{return _OnTextToWrite;}
			set{_OnTextToWrite = value;}
		}

		public string HostName
		{
			get{return _HostName;}
		}

		public IPAddress IP
		{
			get{return _IP;}
		}

		public int Port
		{
			get{return _Port;}
		}

		public string Sent
		{
			get{return _Sent;}
		}

		public string Received
		{
			get{return _Received;}
		}

		public string AsyncReceived
		{
			get{return Encoding.ASCII.GetString(_bReceived, 0, _RecSize);}
		}

		public Connection(string HostName, int Port)
		{
			_StateConn = State.Disconnected;
			_HostName = HostName;
			_Port = Port;
			_bReceived = new byte[1024];

			IPHostEntry HostInfo = Dns.Resolve(HostName);
			_IP = HostInfo.AddressList[0];
		}

		public Connection(IPAddress IP, int Port)
		{
			_StateConn = State.Disconnected;
			_HostName = String.Empty;
			_IP = IP;
			_Port = Port;
			_bReceived = new byte[1024];
		}

		public void Connect()
		{
			if(_StateConn == State.Connected)
				return;

			try
			{
				_TcpConnect = new TcpClient();
				_TcpConnect.Connect(new IPEndPoint(_IP, _Port));
				_Ns = _TcpConnect.GetStream();
				_StateConn = State.Connected;
			}
			catch(Exception e)
			{
				_StateConn = State.Disconnected;
				throw e;
			}
		}

		public void Disconnect()
		{
			try
			{
				_Ns.Close();
				_TcpConnect.Close();
			}
			catch
			{
			}
			finally
			{
				_StateConn = State.Disconnected;
			}
		}

		public void SendToServer(string Text)
		{
			if(_StateConn == State.Disconnected)
				return;

			byte[] bText = Encoding.ASCII.GetBytes(Text.ToCharArray());
			_Sent = Text;

			try
			{
				_Ns.Write(bText, 0, bText.Length);
			}
			catch
			{
				try
				{
					_Ns.Write(bText, 0, bText.Length);
				}
				catch(Exception e)
				{
					_StateConn = State.Disconnected;
					throw e;
				}
			}
		}

		public string GetFromServer()
		{
			if(_StateConn == State.Disconnected)
				return String.Empty;

			StreamReader Sr = null;
			_Received = String.Empty;

			try
			{
				Sr = new StreamReader(_Ns);

				while(Sr.Peek() > -1)
				{
					_Received += Sr.ReadLine() + "\r\n";
				}

				return _Received;
			}
			catch(Exception e)
			{
				_Received = String.Empty;
				throw e;
			}
		}

		public void GetFromServerAsync()
		{
			AsyncCallback Acb = new AsyncCallback(OnReceived);
			_Ns.BeginRead(_bReceived, 0, _bReceived.Length, Acb, _TcpConnect);
		}

		private void OnReceived(IAsyncResult Ar)
		{
			TcpClient Client = (TcpClient)Ar.AsyncState;
			NetworkStream Ns = Client.GetStream();

			int Size = Ns.EndRead(Ar);

			if(Size>0)
			{
				_RecSize = Size;

				if(_OnTextToWrite != null)
					_OnTextToWrite(AsyncReceived);
			
				GetFromServerAsync();
			}
			else
			{
				_StateConn = State.Disconnected;
			}
		}

		public override string ToString()
		{
			return _IP.ToString();
		}
	}
}

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.