.NET中Socket編程的簡單樣本

來源:互聯網
上載者:User
編程|樣本

以下樣本程式實現簡單的Socket通訊,可以開多個用戶端。本機測試通過,未做聯機測試。

Server:

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.Collections;

namespace MySocketServer1

{

    public partial class Form1 : Form

    {

        private IPAddress serverIP = IPAddress.Parse("127.0.0.1");//以本機作測試

        private IPEndPoint serverFullAddr;//完整終端地址

        private Socket sock;

        private System.Timers.Timer myTimer;

        private ArrayList alSock;//當建立了多個串連時用於儲存串連

        public Form1()

        {

            InitializeComponent();

        }

        private void btStart_Click(object sender, EventArgs e)

        {

            serverFullAddr = new IPEndPoint(serverIP, 1000);//取連接埠號碼1000

//構造Socket對象,通訊端類型為“流通訊端”,指定五元組中的協議元

            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

ProtocolType.Tcp);

//指定五元組中的本地二元,即本地主機地址和連接埠號碼

            sock.Bind(serverFullAddr);

//監聽是否有串連傳入,指定掛起的串連隊列的最大值為20

            sock.Listen(20);

            alSock = new ArrayList();

//構造定時器,時間間隙為1秒,即每隔一秒執行一次accept()方法,以擷取串連請求隊列中//第一個掛起的串連請求

            myTimer =new System.Timers.Timer(1000);

            myTimer.Elapsed +=new System.Timers.ElapsedEventHandler(myTimer_Elapsed);

            myTimer.Enabled = true;

        }

        private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

        {

            myTimer.Enabled = false;

//執行accept(),當掛起隊列為空白時將阻塞本線程,同時由於上一語句,定時器將停止,直//至有串連傳入

            Socket acceptSock = sock.Accept();

//將accept()產生的Socket對象存入ArrayList

            alSock.Add(acceptSock);

// 構造Threading.Timer對象,這將導致程式另啟線程。線程將執行回呼函數,該委託限制//函數參數須為object型。Threading.Timer構造器的第二個參數即傳入回呼函數的參數;第//三個參數指定調用回呼函數之前的延時,取0則立即啟動;最後一個參數指定調用回呼函數//的時間間隔,取0則只執行一次。

            System.Threading.Timer ti = new System.Threading.Timer(new

TimerCallback(ReceiveMsg), acceptSock, 0, 0);

            myTimer.Enabled = true;

        }

        private void ReceiveMsg(object obj)

        {

            Socket acceptSock = (Socket)obj;

            try

            {

                while (true)

                {

                    byte[] byteArray = new byte[100];

                    acceptSock.Receive(byteArray);//接收資料

//將位元組數組轉成字串

                    string strRec = System.Text.Encoding.UTF8.GetString(byteArray);

                    if (this.rtbReceive.InvokeRequired)

                    {

                        this.rtbReceive.Invoke(new EventHandler(this.ChangeRickTextBox), new

object[] { strRec, EventArgs.Empty });

                    }

                }

            }

            catch(Exception ex)

            {

                acceptSock.Close();

                MessageBox.Show("S:Receive Message Error"+ex.Message);

            }

        }

        private void ChangeRickTextBox(object obj,EventArgs e)

        {

            string s = System.Convert.ToString(obj);

            this.rtbReceive.AppendText(s + Environment.NewLine);

        }

        private void btSend_Click(object sender, EventArgs e)

        {

            Socket sc=null;

            byte[] byteSend =

System.Text.Encoding.UTF8.GetBytes(this.tbSend.Text.ToCharArray());

            try

            {

//同時存在若干個用戶端串連時,在textBox1中輸入要發送的是哪個串連

                int index = int.Parse(this.textBox1.Text.Trim());

                sc = (Socket)alSock[index - 1];

//發送資料

                sc.Send(byteSend);

            }

            catch(Exception ex)

            {

if(sc != null)

{

                sc.Close();

}

                MessageBox.Show("S:Send Message Error"+ex.Message);

            }

        }

        private void btClose_Click(object sender, EventArgs e)

        {

            try

            {

                Application.Exit();

            }

            catch (Exception ex)

            {

                MessageBox.Show("S:Close Socket Error" + ex.Message);

            }

        }

    }

}

== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==

Client:

using System.Net;

using System.Net.Sockets;

using System.Threading;

namespace MySocketClient1

{

    public partial class Form1 : Form

    {

        private IPAddress serverIP = IPAddress.Parse("127.0.0.1");

        private IPEndPoint serverFullAddr;

        private Socket sock;

        public Form1()

        {

            InitializeComponent();

        }

        private void btConnect_Click(object sender, EventArgs e)

        {

            try

            {

                serverFullAddr = new IPEndPoint(serverIP, 1000);

                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

ProtocolType.Tcp);

                sock.Connect(serverFullAddr);//建立與遠程主機的串連

//啟動新線程用於接收資料

                Thread t = new Thread(new ThreadStart(ReceiveMsg));

                t.Name = "Receive Message";

//一個線程或者是後台線程或者是前台線程。後台線程與前台線程類似,區別是後台線//程不會防止進程終止。一旦屬於某一進程的所有前台線程都終止,公用語言運行庫就//會通過對任何仍然處於活動狀態的後台線程調用 Abort 來結束該進程。

                t.IsBackground = true;

                t.Start();

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        private void ReceiveMsg()

        {

            try

            {

                while (true)

                {

                    byte[] byteRec = new byte[100];

                    this.sock.Receive(byteRec);

                    string strRec = System.Text.Encoding.UTF8.GetString(byteRec);

                    if (this.rtbReceive.InvokeRequired)

                    {

                        this.rtbReceive.Invoke(new EventHandler(ChangeRtb), new object[]

{ strRec, EventArgs.Empty });

                    }

                }

            }

            catch(Exception ex)

            {

                MessageBox.Show("Receive Message Error"+ex.Message);

            }

        }

        private void ChangeRtb(object obj, EventArgs e)

        {

            string s = System.Convert.ToString(obj);

            this.rtbReceive.AppendText(s + Environment.NewLine);

        }

        private void btSend_Click(object sender, EventArgs e)

        {

            byte[] byteSend =

System.Text.Encoding.UTF8.GetBytes(this.tbSend.Text.ToCharArray());

            try

            {

                this.sock.Send(byteSend);

            }

            catch

            {

                MessageBox.Show("Send Message Error");

            }

        }

        private void btClose_Click(object sender, EventArgs e)

        {

            try

            {

                this.sock.Shutdown(SocketShutdown.Receive);

                this.sock.Close();

                Application.Exit();

            }

            catch

            {

                MessageBox.Show("Exit Error");

            }

        }

    }

}

不解之處:

Client端紅色標註語句:this.sock.Shutdown(SocketShutdown.Receive),如改成

this.sock.Shutdown(SocketShutdown.Both);或this.sock.Shutdown(SocketShutdown.Send);

則當點擊Cloce按鈕時,CPU使用率瘋漲到100%,而使用this.sock.Shutdown(SocketShutdown.Receive);

或不調用Shutdown()方法則沒有這個問題。難道用戶端不應該用Shutdown()?



聯繫我們

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