Go directly to the code:
xmal:
<Window x:Class="UDPSocket.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="600" Width="800" WindowStartupLocation="CenterScreen" Closing="MainWindow_Closing"> <Grid> <GroupBox Header="发送数据" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="380" Height="545" Background="AliceBlue"> <StackPanel> <RichTextBox Name="txtSendMssg" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" Height="450" Width="355" Background="White"/> <Button Margin="50 10" Content="发送数据" Height="45" Click="btnSend_Click"/> </StackPanel> </GroupBox> <GroupBox Header="接收数据" HorizontalAlignment="Right" Margin="0,10,10,0" VerticalAlignment="Top" Width="380" Height="545" Background="AliceBlue"> <StackPanel> <RichTextBox Name="txtRecvMssg" HorizontalAlignment="Left" Margin="5,5,5,5" VerticalAlignment="Top" Height="450" Width="355" Background="White"/> <Button Margin="50 10" Content="Receive data/Stop receiving" Height="45" Click="btnRecv_Click"/> </StackPanel> </GroupBox> </Grid> </Window>
Backstage:
using System.Net.Sockets; using System.Net; using System.Threading; using System.Windows.Threading; namespace UDPSocket { /// <summary> /// Interaction logic of MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } /// <summary> /// Network service class for UDP sending /// </summary> private UdpClient udpcSend; /// <summary> /// Network service class for UDP reception /// </summary> private UdpClient udpcRecv; /// <summary> /// button: send data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSend_Click(object sender, EventArgs e) { TextRange tr = new TextRange(txtSendMssg.Document.ContentStart, txtSendMssg.Document.ContentEnd); if (string.IsNullOrWhiteSpace(tr.Text)) { MessageBox.Show("Please enter the content to be sent first"); return; } // send anonymously //udpcSend = new UdpClient(0); // Automatically assign a local IPv4 address // send real name IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234); // Local IP, specified port number udpcSend = new UdpClient(localIpep); Thread thrSend = new Thread(SendMessage); thrSend.Start(tr.Text); } /// <summary> /// send Message /// </summary> /// <param name="obj"></param> private void SendMessage(object obj) { string message = (string)obj; byte[] sendbytes = Encoding.Unicode.GetBytes(message); IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7788); // IP address and port number to send to udpcSend.Send(sendbytes, sendbytes.Length, remoteIpep); udpcSend.Close(); ResetTextBox(txtSendMssg); } /// <summary> /// Switch: true when listening to UDP packets, false otherwise /// </summary> bool IsUdpcRecvStart = false; /// <summary> /// Thread: keep listening for UDP messages /// </summary> Thread thrRecv; /// <summary> /// Button: receive data switch /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRecv_Click(object sender, EventArgs e) { if (!IsUdpcRecvStart) // If not listening, start listening { IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7788); // Local IP and listening port number udpcRecv = new UdpClient(localIpep); thrRecv = new Thread(ReceiveMessage); thrRecv.Start(); IsUdpcRecvStart = true; ShowMessage(txtRecvMssg, "UDP listener started successfully"); } else // If listening, stop listening { thrRecv.Abort(); // This thread must be closed first, otherwise an exception will occur udpcRecv.Close(); IsUdpcRecvStart = false; ShowMessage(txtRecvMssg, "UDP listener closed successfully"); } } /// <summary> /// Receive data /// </summary> /// <param name="obj"></param> private void ReceiveMessage(object obj) { IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0); while (true) { try { byte[] bytRecv = udpcRecv.Receive(ref remoteIpep); string message = Encoding.Unicode.GetString(bytRecv, 0, bytRecv.Length); ShowMessage(txtRecvMssg, string.Format("{0}[{1}]", remoteIpep, message.Trim())); } catch (Exception ex) { ShowMessage(txtRecvMssg, ex.Message); break; } } } // Add text to RichTextBox delegate void ShowMessageDelegate(RichTextBox txtbox, string message); private void ShowMessage(RichTextBox txtbox, string message) { //if (txtbox.InvokeRequired) //{ // ShowMessageDelegate showMessageDelegate = ShowMessage; // txtbox.Dispatcher.Invoke(showMessageDelegate, new object[] { txtbox, message }); //} //else //{ // // txtbox.Text += message + "\r\n"; //} Console.WriteLine(message); } // Clear the text in the specified RichTextBox delegate void ResetTextBoxDelegate(RichTextBox txtbox); private void ResetTextBox(RichTextBox txtbox) { //if (txtbox.InvokeRequired) //{ // ResetTextBoxDelegate resetTextBoxDelegate = ResetTextBox; // txtbox.Dispatcher.Invoke(resetTextBoxDelegate, new object[] { txtbox }); //} //else //{ //// txtbox.Text = ""; //} } /// <summary> /// Close the program, force quit /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Environment.Exit(0); } } }