C# Socket 線程

來源:互聯網
上載者:User
最初的版本是這樣的:點擊開啟連結。但一直沒有調好,所以就諮詢了一下同事翔哥,最後初步搞定!

用戶端代碼:


using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net.Sockets;using System.Threading;using System.Net;using System.Diagnostics;namespace SocketClient{    public partial class Client : Form    {            Socket vsServerSocket;        Thread vsClientThread;        string strIP = "127.0.0.1";        public delegate void PassString(string strMsg);        int nPort = 9001;        public Client()        {            InitializeComponent();        }        public void SetSendData(string strMsg)        {            if (tBoxClientSend.InvokeRequired == true)            {                PassString d = new PassString(SetSendData);                this.Invoke(d, new object[] { strMsg });            }            else            {                tBoxClientSend.Text = strMsg;            }        }        public void SetRecvData(string strMsg)        {            if (tBoxClientReceive.InvokeRequired == true)            {                PassString d = new PassString(SetRecvData);                this.Invoke(d, new object[] { strMsg });            }            else            {                tBoxClientReceive.Text = strMsg;            }        }        private void ClientHandle()        {            string strRecv = string.Empty;            //IPEndPoint其實就是一個IP地址和連接埠的綁定,可以代表一個服務,用來Socket通訊。            //IPAddress類中有一個 Parse()方法,可以把點分的十進位IP表示轉化成IPAddress類            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(strIP), nPort);            //建立通訊端執行個體            //這裡建立的時候用ProtocolType.Tcp,表示建立一個連線導向(TCP)的Socket            vsServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            try            {                //將所建立的通訊端與IPEndPoint綁定                vsServerSocket.Bind(ipep);            }            catch (SocketException ex)            {                MessageBox.Show("Connect Error: " + ex.Message);                return;            }            Byte[] buffer = new Byte[1024];            //設定通訊端為收聽模式            vsServerSocket.Listen(10);            //迴圈監聽               while (true)            {                //接收伺服器資訊                int bufLen = 0;                               try                {                    Socket vsClientSocket = vsServerSocket.Accept();                    bufLen=vsClientSocket.Receive(buffer);                    vsClientSocket.Send(Encoding.ASCII.GetBytes("aaaaa"), 5, SocketFlags.None);                                  }                catch (Exception ex)                {                    MessageBox.Show("Receive Error:" + ex.Message);                                   }                strRecv = Encoding.ASCII.GetString(buffer, 0, bufLen);                SetRecvData(strRecv);                                //vsClientSocket.Shutdown(SocketShutdown.Both);                //vsClientSocket.Close();            }        }        //發送資料        private void btnSend_Click(object sender, EventArgs e)        {            byte[] data = new byte[1024];            string ss = tBoxClientSend.Text;            Socket centerClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            IPEndPoint GsServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9002);            centerClient.Connect(GsServer);            centerClient.Send(Encoding.ASCII.GetBytes(ss));            centerClient.Close();        }        private void Client_Load(object sender, EventArgs e)        {            //串連伺服器            //通過ThreadStart委託告訴子線程講執行什麼方法            vsClientThread = new Thread(new ThreadStart(ClientHandle));            vsClientThread.Start();        }        //表單關閉時殺死用戶端進程        private void Client_FormClosing(object sender, FormClosingEventArgs e)        {            KillProcess();        }        //殺死用戶端進程        private void KillProcess()        {            Process[] processes = Process.GetProcessesByName("SocketClient");            foreach (Process process in processes)            {                process.Kill();                break;            }        }    }}

服務端代碼:



using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;using System.Net.Sockets;using System.Net;using System.Diagnostics;namespace SocketServer{    public partial class Server : Form    {        Thread vsServerThread;        Socket vsServerSocket;              string strIP = "127.0.0.1";        public delegate void PassString(string strMsg);             int nPort = 9002;        public Server()        {            InitializeComponent();        }        private void SeverSendData(string strMsg)        {            //Control.InvokeRequired 屬性,命名空間:  System.Windows.Forms            //擷取一個值,該值指示調用方在對控制項進行方法調用時是否必須調用 Invoke 方法,因為調用方位於建立控制項所在的線程以外的線程中。            if (tBoxServerSend.InvokeRequired == true)            {                //Control.Invoke 方法 (Delegate)                //在擁有此控制項的基礎視窗控制代碼的線程上執行指定的委託。                PassString d = new PassString(SeverSendData);                this.Invoke(d, new object[] { strMsg });            }            else            {                tBoxServerSend.Text = strMsg;            }        }        private void SeverRecvData(string strMsg)        {            if (tBoxServerReceive.InvokeRequired == true)            {                PassString d = new PassString(SeverRecvData);                this.Invoke(d, new object[] { strMsg });            }            else            {                tBoxServerReceive.Text = strMsg;            }        }               private void ServerStart()        {            string strRecv = string.Empty;            //建立IPEndPoint執行個體            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(strIP), nPort);            //建立一個通訊端            vsServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            //將所建立的通訊端與IPEndPoint綁定            try            {                vsServerSocket.Bind(ipep);            }            catch (Exception ee)            {                MessageBox.Show(ee.ToString());                return;            }            //設定通訊端為收聽模式            vsServerSocket.Listen(10);            int bufLen = 0;            //迴圈監聽              while (true)            {                //在通訊端上接收接入的串連                Socket vsClientSocket = vsServerSocket.Accept();                     try                {                                                      Byte[] buffer = new Byte[1024];                    //在通訊端上接收用戶端發送的資訊                    bufLen = vsClientSocket.Receive(buffer);                    vsClientSocket.Send(Encoding.ASCII.GetBytes("aaaaa"), 5, SocketFlags.None);                    if (bufLen == 0)                        continue;                       //將指定位元組數組中的一個位元組序列解碼為一個字串。                    strRecv = Encoding.ASCII.GetString(buffer, 0, bufLen);                    SeverRecvData(strRecv.ToString());                }                catch (Exception ex)                {                    MessageBox.Show("Listening Error: " + ex.Message);                    vsClientSocket.Close();                    vsServerSocket.Close();                }            }        }        private void btnSend_Click(object sender, EventArgs e)        {            byte[] data = new byte[1024];            string ss = tBoxServerSend.Text;            Socket centerClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            IPEndPoint GsServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);            centerClient.Connect(GsServer);            centerClient.Send(Encoding.ASCII.GetBytes(ss));            centerClient.Send(Encoding.ASCII.GetBytes(ss));            //Thread.Sleep(100);            //centerClient.Close();        }        private void Server_Load(object sender, EventArgs e)        {            vsServerThread = new Thread(new ThreadStart(ServerStart));            vsServerThread.Start();        }        //表單關閉時殺死用戶端進程        private void Server_FormClosing(object sender, FormClosingEventArgs e)        {            KillProcess();        }        //殺死用戶端進程        private void KillProcess()        {            Process[] processes = Process.GetProcessesByName("Server");            foreach (Process process in processes)            {                process.Kill();                break;            }        }    }}


效果如下:

用戶端可以發送訊息給服務端,服務端也可以發送訊息給用戶端。

缺點:

現在服務端只能串連一個用戶端

以上就是C# Socket 線程的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.