c#上位機Socket通訊Client封裝

這篇主要介紹一下上位機常見通訊(socket)專案中使用的封裝,經過大量長時間的執行,穩定可靠!!主要封裝了兩個類,ClientClass 和ClientControl(可以擴充套件封裝為組合控制元件使用):

ClientClass 類

using System;using System。Collections。Generic;using System。Linq;using System。Net。Sockets;using System。Text;using System。Net;namespace ClientLib{ public delegate void ClientReceiveData(string ip,string str); public delegate void ClientDisConnect(string ip); [Serializable] public class ClientClass { public event ClientReceiveData eventReceive; public event ClientDisConnect eventDisConnect; private TcpClient client = null; private byte[] str = new byte[10240000]; public bool ConnectServer(string ip, int port) { try { client = new TcpClient(); IAsyncResult ar =client。BeginConnect(IPAddress。Parse(ip), port,null,null); bool ret= ar。AsyncWaitHandle。WaitOne(500); if (!ret) { return false; } Array。Clear(str,0,str。Length); client。GetStream()。BeginRead(str, 0, str。Length, new AsyncCallback(GetData), client); return true; } catch(Exception ex) { System。Windows。Forms。MessageBox。Show(ex。Message); return false; } } private void GetData(IAsyncResult result) { TcpClient tempclient = null; try { tempclient = (TcpClient)result。AsyncState; int lenth = tempclient。GetStream()。EndRead(result); if (lenth == 0) { if (eventDisConnect != null) { eventDisConnect(((IPEndPoint)tempclient。Client。RemoteEndPoint)。Address。ToString()); } client = null; return; } else { if (eventReceive != null) { eventReceive(((IPEndPoint)tempclient。Client。RemoteEndPoint)。Address。ToString(), Encoding。Default。GetString(str)); Array。Clear(str, 0, str。Length); tempclient。GetStream()。BeginRead(str, 0, str。Length, new AsyncCallback(GetData), tempclient); } } } catch { if (eventDisConnect != null) { if (client!=null) { eventDisConnect(((IPEndPoint)tempclient。Client。RemoteEndPoint)。Address。ToString()); } } client = null; } } public bool SendData(string str) { try { if (client != null) { client。GetStream()。Write(Encoding。UTF8。GetBytes(str), 0, Encoding。UTF8。GetBytes(str)。Length); return true; } else { return false; } } catch { return false; } } public void Close() { try { if (client != null) { client。Close(); client= null; } } catch { } } }}

ClientControl類(可以擴充套件為Client控制元件的封裝)

using System;using System。Collections。Generic;using System。Drawing;using System。Data;using System。Linq;using System。Text;using System。Windows。Forms;namespace CommClass{ [Serializable] public class ClientControl { private ClientLib。ClientClass client = new ClientLib。ClientClass(); ///

/// 客戶端狀態 true:連線狀態 false:斷開狀態 /// public bool ClientStatus { private set; get; } /// /// 伺服器傳送過來的資料 /// public string ReceiveStr { private set; get; } public delegate void DeConnectHanle(string ip); public delegate void GetDataHandle(string ip, string receivedata); [Browsable(true)] [Description(“伺服器端斷線時觸發事件”), Category(“自定義事件”)] public event DeConnectHanle DeConnectEvent; [Browsable(true)] [Description(“接收到伺服器端訊息觸發事件”), Category(“自定義事件”)] public event GetDataHandle ReceiveEvent; [Browsable(true)] [Description(“設定伺服器IP地址”), Category(“自定義屬性”)] public string IP { get;set; } [Browsable(true)] [Description(“設定伺服器埠號”), Category(“自定義屬性”)] public string PORT { get;set; } /// /// 連線伺服器 /// /// public bool ConnectServer() { try { if (client。ConnectServer(IP,Convert。ToInt32( PORT))) { ClientStatus = true; return true; } else { ClientStatus = false; return false; } } catch (Exception ex) { ClientStatus = false; MessageBox。Show(ex。Message); return false; } } } /// /// 斷開連線事件 /// /// void client_eventDisConnect(string ip) { if (DeConnectEvent != null) { DeConnectEvent(ip); ClientStatus = false; } } /// /// 接收資料事件 /// /// void client_eventReceive(string ip, string str) { if (ReceiveEvent != null) { ReceiveEvent(ip, str); } } /// /// 斷開與伺服器的連線 /// /// public bool DisConnectServer() { try { client。Close(); ClientStatus = false; return true; } catch (Exception ex) { MessageBox。Show(ex。Message); ClientStatus = false; return false; } } /// /// 傳送資料 /// /// 要傳送的資料 /// 是否傳送成功 true:成功 false:失敗 object obj = new object(); public bool SendData(string str) { lock (obj) { try { client。SendData(str); return true; } catch (Exception ex) { MessageBox。Show(ex。Message); return false; } } } public ClientControl() { client。eventReceive += new ClientLib。ClientReceiveData(client_eventReceive); client。eventDisConnect += new ClientLib。ClientDisConnect(client_eventDisConnect); } }}

上面兩個功能封裝成的Client底層

在程式中使用

1。匯入名稱空間

using CommClass;using System。IO。Ports;using System。Threading;using System。Net。Sockets;using System。Net;

2。建立物件

public static ClientControl ClientOfLeftCCD = new ClientControl();

3。初始化引數繫結接受資料事件和伺服器斷開事件

ClientOfLeftCCD。ReceiveEvent += new CommClass。ClientControl。GetDataHandle(RecFromLeftCCD); ClientOfLeftCCD。DeConnectEvent += new CommClass。ClientControl。DeConnectHanle(DisCntFromCCD); ClientOfLeftCCD。IP = GlobClass。m_sLeftCCDIP。PValue;//與前面文章講到的單控制元件引數繫結一起使用更方便 ClientOfLeftCCD。PORT = GlobClass。m_sLeftCCDPort。PValue;//與前面文章講到的單控制元件引數繫結一起使用更方

4。事件觸發接收函式

///

/// 接收左CCD返回來的資料 /// /// /// private static void RecFromLeftCCD(string IP, string info) { if (info != null) { info = info。Trim(‘\0’); …………………………………………。。 } } private static void DisCntFromCCD(string IP) { //斷開與CCD的伺服器的連結 }

5。連線伺服器

if (!ClientOfLeftRobot。ClientStatus){ ClientOfLeftRobot。ConnectServer();}

希望與大家多交流交流……