1. 程式人生 > >C# UDP接收和傳送

C# UDP接收和傳送

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System

.NET;
using System.Net.Sockets;
using System.Threading;

namespace WpfTest
{
    /// <summary>
    /// Window1.xaml 的互動邏輯
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            Thread thread1 = new Thread(new ThreadStart(ReceiveData));
            thread1.Start();
        }
        delegate void TextBoxCallback(string str);
        public void SetTextBox(string str)
        {
            textBox1.Text = str;

        }
        private int port = 62001;
        private UdpClient udpClient;
        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);
                    TextBoxCallback tx = SetTextBox;
                    this.Dispatcher.Invoke(tx, str);
                }
                catch
                {
                    //退出迴圈,結束執行緒
                    break;
                }
                finally
                {
                    udpClient.Close();
                }
            }
        }

        private void sendData()
        {
            UdpClient myUdpClient = new UdpClient();
            IPAddress remoteIP;
            if (IPAddress.TryParse(textBoxRemoteIP.Text, out remoteIP) == false)
            {
                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);
                textBoxSend.Clear();
                myUdpClient.Close();
                textBoxSend.Focus();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "傳送失敗");
            }
            finally
            {
                myUdpClient.Close();
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            sendData();
        }
    }
}