『原創』C# wm6通過udp協議和pc通訊

來源:互聯網
上載者:User

本文主要介紹了如何使用udp協議,多線程,讓ppc和pc在同一區域網路進行簡單的文字收發。

我們要做好如下設定,因為是用模擬器來配置網路環境,你還必須參考下面這篇文章進行模擬器網路環境配置:點擊察看

說明:我的PPC端ip是192.168.0.102,伺服器端為192.168.0.100,請根據實際情況配置。

配置好後,就可以開始我們的編程了。

設計用戶端(PPC 端)如:

代碼如下:

 

PPC Code
namespace SimpleTcp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            listBoxCallback = new AddListBoxItemCallback(AddListBoxItem);
        }
       // string senddate,readdate;
        
       // NetworkStream ns;
        delegate void AddListBoxItemCallback(string text);
        AddListBoxItemCallback listBoxCallback;
        private int port = 8001;
        private UdpClient udpClient;

        private void AddListBoxItem(string text)
        {
            //如果listBoxReceive被不同的線程訪問則通過委託處理;
            if (listBoxReceive.InvokeRequired)
            {
                this.Invoke(listBoxCallback, text);
            }
            else
            {
                listBoxReceive.Items.Add(text);
                listBoxReceive.SelectedIndex = listBoxReceive.Items.Count - 1;
            }
        }

        private void ReceiveData()
        {
            //在本機指定的連接埠接收
            udpClient = new UdpClient(port);
            IPEndPoint remote = null;
            //接收從遠程主機發送過來的資訊;
            while (true)
            {
                try
                {
                    //關閉udpClient時此句會產生異常
                    byte[] bytes = udpClient.Receive(ref remote);
                    string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    AddListBoxItem(string.Format("來自{0}:{1}", remote, str));
                }
                catch
                {
                    //退出迴圈,結束線程
                    break;
                }
            }
        }

        /// 發送資料到遠程主機
        /// </summary>
        private void sendData()
        {
            UdpClient myUdpClient = new UdpClient();
            IPAddress remoteIP=IPAddress.Parse(textBoxRemoteIP.Text);
            if ( remoteIP== null)
            {
                MessageBox.Show("遠程IP格式不正確");
                return;
            }
            IPEndPoint iep = new IPEndPoint(remoteIP, port);
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBoxSend.Text);
            try
            {
                myUdpClient.Send(bytes, bytes.Length, iep);
                
                myUdpClient.Close();
                textBoxSend.Focus();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "發送失敗");
            }
            finally
            {
                myUdpClient.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            udpClient.Close();
            Application.Exit();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            sendData();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
          
           
            //擷取本機第一個可用IP地址
            IPAddress myIP = IPAddress.Parse("192.168.0.100");
            //為了在同一台機器調試,此IP也作為預設遠程IP
            textBoxRemoteIP.Text = myIP.ToString();
            //建立一個線程接收遠程主機發來的資訊
            Thread myThread = new Thread(new ThreadStart(ReceiveData));
            //將線程設為後台運行
            myThread.IsBackground = true;
            myThread.Start();
            textBoxSend.Focus();

        }
    }
}

 

 

用戶端就ok了。

 

下面我們寫伺服器端,代碼和用戶端基本一致,就不贅述了,伺服器端設計介面如下:

最終效果如:

轉載(如果有人轉載)請註明出處吧,謝謝。

相關文章

聯繫我們

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