C#使用wpf写一个udpclient一个项目写服务端另一个项目写客户端收发信息
时间: 2024-05-03 12:17:50 浏览: 111
C# 做的Udp实例,有服务器端和客户端
3星 · 编辑精心推荐
好的,下面是一个简单的示例,演示如何使用C#和WPF编写UDP客户端和服务器:
UDP客户端示例:
```c#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
namespace UdpClientExample
{
public partial class MainWindow : Window
{
private UdpClient udpClient;
private IPEndPoint serverEndPoint;
public MainWindow()
{
InitializeComponent();
// 初始化UDP客户端
udpClient = new UdpClient();
serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
}
private void SendButton_Click(object sender, RoutedEventArgs e)
{
try
{
// 将文本框中的消息转换为字节数组
byte[] messageBytes = Encoding.ASCII.GetBytes(MessageTextBox.Text);
// 发送消息到服务器
udpClient.Send(messageBytes, messageBytes.Length, serverEndPoint);
// 显示发送消息的信息
MessageListBox.Items.Add($"[SENT] {MessageTextBox.Text}");
}
catch (Exception ex)
{
MessageBox.Show($"Error sending message: {ex.Message}");
}
}
private void ReceiveButton_Click(object sender, RoutedEventArgs e)
{
try
{
// 接收服务器的消息
byte[] receivedBytes = udpClient.Receive(ref serverEndPoint);
// 将接收到的字节数组转换为字符串
string receivedMessage = Encoding.ASCII.GetString(receivedBytes);
// 显示接收到的消息
MessageListBox.Items.Add($"[RECEIVED] {receivedMessage}");
}
catch (Exception ex)
{
MessageBox.Show($"Error receiving message: {ex.Message}");
}
}
}
}
```
UDP服务器示例:
```c#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
namespace UdpServerExample
{
public partial class MainWindow : Window
{
private UdpClient udpServer;
private IPEndPoint clientEndPoint;
private Thread receiveThread;
public MainWindow()
{
InitializeComponent();
// 初始化UDP服务器
udpServer = new UdpClient(8888);
clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
// 开始接收消息
receiveThread = new Thread(ReceiveMessages);
receiveThread.Start();
}
private void ReceiveMessages()
{
try
{
while (true)
{
// 接收客户端的消息
byte[] receivedBytes = udpServer.Receive(ref clientEndPoint);
// 将接收到的字节数组转换为字符串
string receivedMessage = Encoding.ASCII.GetString(receivedBytes);
// 在UI线程中显示接收到的消息
Dispatcher.Invoke(() => MessageListBox.Items.Add($"[RECEIVED] {receivedMessage}"));
}
}
catch (Exception ex)
{
MessageBox.Show($"Error receiving message: {ex.Message}");
}
}
}
}
```
这两个示例应该可以帮助你入门UDP编程。由于这里只是一个简单的示例,因此在实际应用中可能需要进行更多的错误处理和安全性检查。
阅读全文