C# Socket通訊用戶端類、伺服器類

來源:互聯網
上載者:User

         其實這些東西網上都有,但是比較淩亂,很少有封裝好的類,在此共用一下。。。

         一個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!");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.