TcpClient, c # tcpclient
Public class TcpClientSession {protected TcpClient Client {get; set ;}/// <summary> /// remote address /// </summary> protected IPEndPoint RemoteEndPoint {get; set ;} /// <summary> /// whether the connection has been established /// </summary> public bool IsConnected {get; private set ;} /// <summary> /// size of the receiving cache /// </summary> public int ReceiveBufferSize = 1024; /// <summary> // data stream object // </summary> protected NetworkStream _ NetStream ;/ // <Summary> /// connected event /// </summary> public event Action OnConnected; /// <summary> // disconnect event // </summary> public event Action OnClosed; public TcpClientSession (IPEndPoint remoteEndPoint) {if (remoteEndPoint = null) throw new ArgumentNullException ("remoteEndPoint"); RemoteEndPoint = remoteEndPoint;} public TcpClientSession (string server, int port) {if (server! = Null & port> 0) {if (! Regex. isMatch (server, @ "(\ d {1, 3 })\. (\ d {1, 3 })\. (\ d {1, 3 })\. (\ d {1, 3}) ") {try {IPHostEntry ipHostEntry = System. net. dns. getHostEntry (server); server = ipHostEntry. addressList [0]. toString () ;}catch (Exception) {throw new ArgumentNullException ("the remote IP address or domain name is incorrect") ;}} RemoteEndPoint = new IPEndPoint (IPAddress. parse (server), port);} else throw new ArgumentNullException ("remoteEndPoint");} public void C Onnect () {Client = new TcpClient (RemoteEndPoint. addressFamily); Client. receiveBufferSize = ReceiveBufferSize; Client. connect (RemoteEndPoint); if (Client. client. connected) {_ NetStream = Client. getStream (); IsConnected = true; if (this. onConnected! = Null) OnConnected ();} else throw new Exception ("Unable to connect to a remote device");} public byte [] stored ed () {if (Client. client. connected) {byte [] buffer = null; buffer = new byte [ReceiveBufferSize]; _ NetStream. read (buffer, 0, buffer. length); return buffer;} else {Close ();} return null;} public void Send (byte [] bs) {if (Client. client. connected) {_ NetStream. write (bs, 0, bs. length );} Else {Close () ;}} public void Close () {if (Client. client. connected) {Client. close (); _ NetStream. close ();} IsConnected = false; if (this. onClosed! = Null) OnClosed ();}}