其實這些東西網上都有,但是比較淩亂,很少有封裝好的類,在此共用一下。。。
一個Socket伺服器類,一個Socket用戶端類,都可以直接拿去用,下邊有詳細的調用樣本。
需要說明的是,伺服器類沒有處理多客戶串連,只是簡單的響應單客戶串連。
另外,提醒一點,尤其是很多新手容易犯的錯誤,就是伺服器類處理事務是線上程中進行的,此時不能訪問介面上的控制項,需要委託跨線程訪問。
Socket伺服器類(SocketServicesHelper.cs):
using System;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Diagnostics;using System.Text.RegularExpressions;namespace USBControl{ /// <summary> /// Socket伺服器類 /// </summary> public class SocketServicesHelper { private Socket socket1 = null; private Socket socket2 = null; private Thread ListenThread = null; private int port = 0; //監聽連接埠 /// <summary> /// 構造方法 /// </summary> /// <param name="port">監聽連接埠</param> public SocketServicesHelper(int port) { this.port = port; } /// <summary> /// 啟動服務 /// </summary> public void startServices() { try { //擷取本機IP IPAddress ip = IPAddress.Parse(getIP()); //步驟1 建立網路端點IPEndPoint IPEndPoint myServer = new IPEndPoint(ip, port); //步驟2 建立通訊端Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //步驟3 通訊端綁定到網路端點 socket1.Bind(myServer); //建立監聽線程 ListenThread = new Thread(new ThreadStart(ListenFunction)); //啟動線程 ListenThread.Start(); } catch (Exception ex) { throw ex; } } /// <summary> /// 監聽方法,線上程中啟動 /// </summary> void ListenFunction() { try { clsUSBControl usbcl = new clsUSBControl(); RegChangeNotice regChangeNotice = new RegChangeNotice(); //步驟4 設定最大用戶端串連數 socket1.Listen(5); //迴圈檢測用戶端串連 while (true) { //步驟5 檢測用戶端串連 socket2 = socket1.Accept(); //步驟6 判斷串連狀態 if (socket2.Connected) { //步驟7 接收用戶端訊息 byte[] clientData = new byte[1024]; int i = socket2.Receive(clientData); string removeMsg = Encoding.Unicode.GetString(clientData, 0, i).Split(new char[] { '|' })[0].Split(new char[] { ' ' })[1]; //根據訊息做出相應動作 } } } catch (Exception ex) { throw ex; } finally { //關閉串連 if (socket1.Connected) { socket1.Shutdown(SocketShutdown.Both); socket1.Close(); } if (socket2.Connected) { socket2.Shutdown(SocketShutdown.Both); socket2.Close(); } } } /// <summary> /// 獲得本機IP地址 /// </summary> /// <returns></returns> private string getIP() { string ipAddress = ""; Process p = null; StreamReader reader = null; try { ProcessStartInfo start = new ProcessStartInfo("cmd.exe"); start.FileName = "ipconfig"; start.Arguments = "/all"; start.CreateNoWindow = true; start.RedirectStandardOutput = true; start.RedirectStandardInput = true; start.UseShellExecute = false; p = Process.Start(start); reader = p.StandardOutput; string line = reader.ReadLine(); while (!reader.EndOfStream) { if (line.ToLower().IndexOf("ip address") > 0 || line.ToLower().IndexOf("ipv4 地址") > 0 || line.ToLower().IndexOf("ip地址") > 0) { int index = line.IndexOf(":"); index += 2; ipAddress = ipAddress + line.Substring(index) + ","; } line = reader.ReadLine(); } } catch(Exception ex) { throw ex; } finally { if (p != null) { p.WaitForExit(); p.Close(); } if (reader != null) { reader.Close(); } } return Regex.Match(ipAddress.Equals("") ? ipAddress : ipAddress.Substring(0, ipAddress.Length - 1), "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}").ToString(); } }}
調用樣本:
//執行個體化時傳入監聽連接埠,本機IP自動擷取
SocketServicesHelper ssh = new SocketServicesHelper(8881);
//開始監聽
ssh. startServices();
Socket 用戶端類(SocketClientHelper.cs):
using System;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;namespace BLL{ /// <summary> /// Socket用戶端類 /// </summary> public class SocketClientHelper { private IPAddress ip = null; private int port = 0; private Socket socket = null; /// <summary> /// 構造方法 /// </summary> /// <param name="ip">伺服器IP</param> /// <param name="port">伺服器連接埠</param> public SocketClientHelper(IPAddress ip, int port) { this.ip = ip; this.port = port; } /// <summary> /// 向伺服器發送訊息 /// </summary> /// <param name="sendStr">訊息內容</param> /// <returns></returns> public string send(string sendStr) { try { LayerParameter lp = new LayerParameter(); IPEndPoint removeServer = new IPEndPoint(ip, port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(removeServer); //檢查串連狀態 if (socket.Connected) { //轉換編碼 byte[] bs = Encoding.Unicode.GetBytes(sendStr); //發送訊息 socket.Send(bs, bs.Length, 0); //斷開SOCKET socket.Shutdown(SocketShutdown.Both); //關閉SOCKET socket.Close(); return "設定成功!"; } else { return "與用戶端通訊失敗,可能是電腦未開啟或者用戶端未開啟!"; } } catch (Exception ex) { throw ex; } } }}
調用樣本:
//執行個體化時傳入伺服器IP和訊息連接埠
SocketClientHelper sch = new SocketClientHelper(IPAddress.Parse("192.168.24.177"),8881);
//發送訊息
sch.send("Hello Word!");