這篇文章主要介紹了C#中Socket框架怎么用,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
創(chuàng)新互聯(lián)主營(yíng)威寧網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,app軟件開(kāi)發(fā),威寧h5小程序定制開(kāi)發(fā)搭建,威寧網(wǎng)站營(yíng)銷(xiāo)推廣歡迎威寧等地區(qū)企業(yè)咨詢(xún)
。
前言
一說(shuō)到Socket,想必大家都或多或少有所涉及,從最初的計(jì)算機(jī)網(wǎng)絡(luò)課程,講述了tcp協(xié)議,而Socket就是對(duì)協(xié)議的進(jìn)一步封裝,使我們開(kāi)發(fā)人員能夠更加容易輕松的進(jìn)行軟件之間的通信。
這個(gè)星期剛好接受一個(gè)共享車(chē)位鎖的項(xiàng)目,需要使用Socket與硬件進(jìn)行通信控制,說(shuō)白了也就是給鎖發(fā)送指令,控制其打開(kāi)或者關(guān)閉,再就是對(duì)App開(kāi)放操作接口,使其方便測(cè)試以及用戶(hù)的使用。這其中核心就是Socket的使用,再開(kāi)發(fā)出這個(gè)功能之后,我發(fā)現(xiàn)使用起來(lái)很不方便,于是耗時(shí)2天抽象其核心功能并封裝成框架,最后使用這個(gè)框架將原來(lái)的項(xiàng)目重構(gòu)并上線(xiàn),極大的提高了軟件的可拓展性,健壯性,容錯(cuò)率。
個(gè)人堅(jiān)信的原則:萬(wàn)物皆對(duì)象
好了,不廢話(huà)了,下面進(jìn)入正文
正文:
1、首先簡(jiǎn)單講下C#中Socket的簡(jiǎn)單使用。
第一步:服務(wù)端監(jiān)聽(tīng)某個(gè)端口
第二步:客戶(hù)端向服務(wù)端地址和端口發(fā)起Socket連接請(qǐng)求
第三步:服務(wù)端收到連接請(qǐng)求后創(chuàng)建Socket連接,并維護(hù)這個(gè)連接隊(duì)列。
第四步:客戶(hù)端和服務(wù)端已經(jīng)建立雙工通信(即雙向通信),客戶(hù)端和服務(wù)端可以輕松方便的給彼此發(fā)送信息。
至于簡(jiǎn)單使用的具體實(shí)現(xiàn)代碼全部被我封裝到項(xiàng)目中了,如果需要學(xué)習(xí)簡(jiǎn)單的實(shí)現(xiàn),可以看我的源碼,也可以自行百度,有很多的教程
2、核心,框架的使用
其實(shí),說(shuō)其為框架,可能有點(diǎn)牽強(qiáng),因?yàn)槊總€(gè)人對(duì)框架都有自己的理解,但是類(lèi)庫(kù)和框架又有什么本質(zhì)區(qū)別呢?全部都是代碼~哈哈,扯遠(yuǎn)了
首先,空說(shuō)無(wú)憑,先放上所有的代碼:
服務(wù)端源文件:
SocketServer.cs
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; namespace Coldairarrow.Util.Sockets { ////// Socket服務(wù)端 /// public class SocketServer { #region 構(gòu)造函數(shù) ////// 構(gòu)造函數(shù) /// /// 監(jiān)聽(tīng)的IP地址 /// 監(jiān)聽(tīng)的端口 public SocketServer(string ip, int port) { _ip = ip; _port = port; } ////// 構(gòu)造函數(shù),監(jiān)聽(tīng)I(yíng)P地址默認(rèn)為本機(jī)0.0.0.0 /// /// 監(jiān)聽(tīng)的端口 public SocketServer(int port) { _ip = "0.0.0.0"; _port = port; } #endregion #region 內(nèi)部成員 private Socket _socket = null; private string _ip = ""; private int _port = 0; private bool _isListen = true; private void StartListen() { try { _socket.BeginAccept(asyncResult => { try { Socket newSocket = _socket.EndAccept(asyncResult); //馬上進(jìn)行下一輪監(jiān)聽(tīng),增加吞吐量 if (_isListen) StartListen(); SocketConnection newClient = new SocketConnection(newSocket, this) { HandleRecMsg = HandleRecMsg == null ? null : new Action(HandleRecMsg), HandleClientClose = HandleClientClose == null ? null : new Action (HandleClientClose), HandleSendMsg = HandleSendMsg == null ? null : new Action (HandleSendMsg), HandleException = HandleException == null ? null : new Action (HandleException) }; newClient.StartRecMsg(); ClientList.AddLast(newClient); HandleNewClientConnected?.Invoke(this, newClient); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } } #endregion #region 外部接口 /// /// 開(kāi)始服務(wù),監(jiān)聽(tīng)客戶(hù)端 /// public void StartServer() { try { //實(shí)例化套接字(ip4尋址協(xié)議,流式傳輸,TCP協(xié)議) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //創(chuàng)建ip對(duì)象 IPAddress address = IPAddress.Parse(_ip); //創(chuàng)建網(wǎng)絡(luò)節(jié)點(diǎn)對(duì)象包含ip和port IPEndPoint endpoint = new IPEndPoint(address, _port); //將 監(jiān)聽(tīng)套接字綁定到 對(duì)應(yīng)的IP和端口 _socket.Bind(endpoint); //設(shè)置監(jiān)聽(tīng)隊(duì)列長(zhǎng)度為Int32最大值(同時(shí)能夠處理連接請(qǐng)求數(shù)量) _socket.Listen(int.MaxValue); //開(kāi)始監(jiān)聽(tīng)客戶(hù)端 StartListen(); HandleServerStarted?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } } ////// 所有連接的客戶(hù)端列表 /// public LinkedListClientList { get; set; } = new LinkedList (); /// /// 關(guān)閉指定客戶(hù)端連接 /// /// 指定的客戶(hù)端連接 public void CloseClient(SocketConnection theClient) { theClient.Close(); } #endregion #region 公共事件 ////// 異常處理程序 /// public ActionHandleException { get; set; } #endregion #region 服務(wù)端事件 /// /// 服務(wù)啟動(dòng)后執(zhí)行 /// public ActionHandleServerStarted { get; set; } /// /// 當(dāng)新客戶(hù)端連接后執(zhí)行 /// public ActionHandleNewClientConnected { get; set; } /// /// 服務(wù)端關(guān)閉客戶(hù)端后執(zhí)行 /// public ActionHandleCloseClient { get; set; } #endregion #region 客戶(hù)端連接事件 /// /// 客戶(hù)端連接接受新的消息后調(diào)用 /// public ActionHandleRecMsg { get; set; } /// /// 客戶(hù)端連接發(fā)送消息后回調(diào) /// public ActionHandleSendMsg { get; set; } /// /// 客戶(hù)端連接關(guān)閉后回調(diào) /// public ActionHandleClientClose { get; set; } #endregion } }
using System; using System.Net.Sockets; using System.Text; namespace Coldairarrow.Util.Sockets { ////// Socket連接,雙向通信 /// public class SocketConnection { #region 構(gòu)造函數(shù) public SocketConnection(Socket socket,SocketServer server) { _socket = socket; _server = server; } #endregion #region 私有成員 private readonly Socket _socket; private bool _isRec=true; private SocketServer _server = null; private bool IsSocketConnected() { bool part1 = _socket.Poll(1000, SelectMode.SelectRead); bool part2 = (_socket.Available == 0); if (part1 && part2) return false; else return true; } #endregion #region 外部接口 ////// 開(kāi)始接受客戶(hù)端消息 /// public void StartRecMsg() { try { byte[] container = new byte[1024 * 1024 * 2]; _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult => { try { int length = _socket.EndReceive(asyncResult); //馬上進(jìn)行下一輪接受,增加吞吐量 if (length > 0 && _isRec && IsSocketConnected()) StartRecMsg(); if (length > 0) { byte[] recBytes = new byte[length]; Array.Copy(container, 0, recBytes, 0, length); //處理消息 HandleRecMsg?.Invoke(recBytes, this, _server); } else Close(); } catch (Exception ex) { HandleException?.Invoke(ex); Close(); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); Close(); } } ////// 發(fā)送數(shù)據(jù) /// /// 數(shù)據(jù)字節(jié) public void Send(byte[] bytes) { try { _socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult => { try { int length = _socket.EndSend(asyncResult); HandleSendMsg?.Invoke(bytes, this, _server); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } } ////// 發(fā)送字符串(默認(rèn)使用UTF-8編碼) /// /// 字符串 public void Send(string msgStr) { Send(Encoding.UTF8.GetBytes(msgStr)); } ////// 發(fā)送字符串(使用自定義編碼) /// /// 字符串消息 /// 使用的編碼 public void Send(string msgStr,Encoding encoding) { Send(encoding.GetBytes(msgStr)); } ////// 傳入自定義屬性 /// public object Property { get; set; } ////// 關(guān)閉當(dāng)前連接 /// public void Close() { try { _isRec = false; _socket.Disconnect(false); _server.ClientList.Remove(this); HandleClientClose?.Invoke(this, _server); _socket.Close(); _socket.Dispose(); GC.Collect(); } catch (Exception ex) { HandleException?.Invoke(ex); } } #endregion #region 事件處理 ////// 客戶(hù)端連接接受新的消息后調(diào)用 /// public ActionHandleRecMsg { get; set; } /// /// 客戶(hù)端連接發(fā)送消息后回調(diào) /// public ActionHandleSendMsg { get; set; } /// /// 客戶(hù)端連接關(guān)閉后回調(diào) /// public ActionHandleClientClose { get; set; } /// /// 異常處理程序 /// public ActionHandleException { get; set; } #endregion } }
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Coldairarrow.Util.Sockets { ////// Socket客戶(hù)端 /// public class SocketClient { #region 構(gòu)造函數(shù) ////// 構(gòu)造函數(shù),連接服務(wù)器IP地址默認(rèn)為本機(jī)127.0.0.1 /// /// 監(jiān)聽(tīng)的端口 public SocketClient(int port) { _ip = "127.0.0.1"; _port = port; } ////// 構(gòu)造函數(shù) /// /// 監(jiān)聽(tīng)的IP地址 /// 監(jiān)聽(tīng)的端口 public SocketClient(string ip, int port) { _ip = ip; _port = port; } #endregion #region 內(nèi)部成員 private Socket _socket = null; private string _ip = ""; private int _port = 0; private bool _isRec=true; private bool IsSocketConnected() { bool part1 = _socket.Poll(1000, SelectMode.SelectRead); bool part2 = (_socket.Available == 0); if (part1 && part2) return false; else return true; } ////// 開(kāi)始接受客戶(hù)端消息 /// public void StartRecMsg() { try { byte[] container = new byte[1024 * 1024 * 2]; _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult => { try { int length = _socket.EndReceive(asyncResult); //馬上進(jìn)行下一輪接受,增加吞吐量 if (length > 0 && _isRec && IsSocketConnected()) StartRecMsg(); if (length > 0) { byte[] recBytes = new byte[length]; Array.Copy(container, 0, recBytes, 0, length); //處理消息 HandleRecMsg?.Invoke(recBytes, this); } else Close(); } catch (Exception ex) { HandleException?.Invoke(ex); Close(); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); Close(); } } #endregion #region 外部接口 ////// 開(kāi)始服務(wù),連接服務(wù)端 /// public void StartClient() { try { //實(shí)例化 套接字 (ip4尋址協(xié)議,流式傳輸,TCP協(xié)議) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //創(chuàng)建 ip對(duì)象 IPAddress address = IPAddress.Parse(_ip); //創(chuàng)建網(wǎng)絡(luò)節(jié)點(diǎn)對(duì)象 包含 ip和port IPEndPoint endpoint = new IPEndPoint(address, _port); //將 監(jiān)聽(tīng)套接字 綁定到 對(duì)應(yīng)的IP和端口 _socket.BeginConnect(endpoint, asyncResult => { try { _socket.EndConnect(asyncResult); //開(kāi)始接受服務(wù)器消息 StartRecMsg(); HandleClientStarted?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } } ////// 發(fā)送數(shù)據(jù) /// /// 數(shù)據(jù)字節(jié) public void Send(byte[] bytes) { try { _socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult => { try { int length = _socket.EndSend(asyncResult); HandleSendMsg?.Invoke(bytes, this); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } } ////// 發(fā)送字符串(默認(rèn)使用UTF-8編碼) /// /// 字符串 public void Send(string msgStr) { Send(Encoding.UTF8.GetBytes(msgStr)); } ////// 發(fā)送字符串(使用自定義編碼) /// /// 字符串消息 /// 使用的編碼 public void Send(string msgStr, Encoding encoding) { Send(encoding.GetBytes(msgStr)); } ////// 傳入自定義屬性 /// public object Property { get; set; } ////// 關(guān)閉與服務(wù)器的連接 /// public void Close() { try { _isRec = false; _socket.Disconnect(false); HandleClientClose?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } } #endregion #region 事件處理 ////// 客戶(hù)端連接建立后回調(diào) /// public ActionHandleClientStarted { get; set; } /// /// 處理接受消息的委托 /// public ActionHandleRecMsg { get; set; } /// /// 客戶(hù)端連接發(fā)送消息后回調(diào) /// public ActionHandleSendMsg { get; set; } /// /// 客戶(hù)端連接關(guān)閉后回調(diào) /// public ActionHandleClientClose { get; set; } /// /// 異常處理程序 /// public ActionHandleException { get; set; } #endregion } }
上面放上的是框架代碼,接下來(lái)介紹下如何使用
首先,服務(wù)端使用方式:
using Coldairarrow.Util.Sockets; using System; using System.Text; namespace Console_Server { class Program { static void Main(string[] args) { //創(chuàng)建服務(wù)器對(duì)象,默認(rèn)監(jiān)聽(tīng)本機(jī)0.0.0.0,端口12345 SocketServer server = new SocketServer(12345); //處理從客戶(hù)端收到的消息 server.HandleRecMsg = new Action((bytes, client, theServer) => { string msg = Encoding.UTF8.GetString(bytes); Console.WriteLine($"收到消息:{msg}"); }); //處理服務(wù)器啟動(dòng)后事件 server.HandleServerStarted = new Action (theServer => { Console.WriteLine("服務(wù)已啟動(dòng)************"); }); //處理新的客戶(hù)端連接后的事件 server.HandleNewClientConnected = new Action ((theServer, theCon) => { Console.WriteLine($@"一個(gè)新的客戶(hù)端接入,當(dāng)前連接數(shù):{theServer.ClientList.Count}"); }); //處理客戶(hù)端連接關(guān)閉后的事件 server.HandleClientClose = new Action ((theCon, theServer) => { Console.WriteLine($@"一個(gè)客戶(hù)端關(guān)閉,當(dāng)前連接數(shù)為:{theServer.ClientList.Count}"); }); //處理異常 server.HandleException = new Action (ex => { Console.WriteLine(ex.Message); }); //服務(wù)器啟動(dòng) server.StartServer(); while (true) { Console.WriteLine("輸入:quit,關(guān)閉服務(wù)器"); string op = Console.ReadLine(); if (op == "quit") break; } } } }
客戶(hù)端使用方式:
using Coldairarrow.Util.Sockets; using System; using System.Text; namespace Console_Client { class Program { static void Main(string[] args) { //創(chuàng)建客戶(hù)端對(duì)象,默認(rèn)連接本機(jī)127.0.0.1,端口為12345 SocketClient client = new SocketClient(12345); //綁定當(dāng)收到服務(wù)器發(fā)送的消息后的處理事件 client.HandleRecMsg = new Action((bytes, theClient) => { string msg = Encoding.UTF8.GetString(bytes); Console.WriteLine($"收到消息:{msg}"); }); //綁定向服務(wù)器發(fā)送消息后的處理事件 client.HandleSendMsg = new Action ((bytes, theClient) => { string msg = Encoding.UTF8.GetString(bytes); Console.WriteLine($"向服務(wù)器發(fā)送消息:{msg}"); }); //開(kāi)始運(yùn)行客戶(hù)端 client.StartClient(); while (true) { Console.WriteLine("輸入:quit關(guān)閉客戶(hù)端,輸入其它消息發(fā)送到服務(wù)器"); string str = Console.ReadLine(); if (str == "quit") { client.Close(); break; } else { client.Send(str); } } } } }
最后運(yùn)行測(cè)試截圖:
總結(jié):
其最方便之處在于,將如何創(chuàng)建連接封裝掉,使用人員只需關(guān)注連接后發(fā)送什么數(shù)據(jù),接收到數(shù)據(jù)后應(yīng)該如何處理,等等其它的很多事件的處理,這其中主要依托于匿名委托的使用,Lambda表達(dá)式的使用。
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“C#中Socket框架怎么用”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!