C#窗体程序,创建UDP发送端,按钮1发送数据“play”到目标IP地址"192.168.10.100"和端口号8001,按钮2发送数据“pause”到目标IP地址"192.168.10.88"和端口号777,IP和端口在App.config配置文件里的完整代码
时间: 2024-09-20 18:01:53 浏览: 49
在C#中,要创建一个UDP发送端的窗体程序,并从两个不同的按钮发送数据到指定的IP地址,你需要做以下步骤:
1. 首先,在App.config文件中添加网络连接信息作为配置节点:
```xml
<configuration>
<appSettings>
<add key="TargetIP1" value="192.168.10.100" />
<add key="TargetPort1" value="8001" />
<add key="TargetIP2" value="192.168.10.88" />
<add key="TargetPort2" value="777" />
</appSettings>
</configuration>
```
2. 创建一个UdpClient类实例,用于发送数据:
```csharp
using System.Net;
using System.Net.Sockets;
public partial class MainForm : Form
{
private UdpClient udpClient1;
private UdpClient udpClient2;
public MainForm()
{
InitializeComponent();
InitializeUdpClients();
}
private void InitializeUdpClients()
{
IPAddress ip1 = IPAddress.Parse(ConfigurationManager.AppSettings["TargetIP1"]);
int port1 = int.Parse(ConfigurationManager.AppSettings["TargetPort1"]);
udpClient1 = new UdpClient(port1);
udpClient1.Connect(ip1, port1);
IPAddress ip2 = IPAddress.Parse(ConfigurationManager.AppSettings["TargetIP2"]);
int port2 = int.Parse(ConfigurationManager.AppSettings["TargetPort2"]);
udpClient2 = new UdpClient(port2);
udpClient2.Connect(ip2, port2);
}
//...
}
```
3. 给每个按钮绑定事件处理函数,分别发送数据:
```csharp
private async void ButtonSendPlay_Click(object sender, EventArgs e)
{
string data = "play";
await SendData(udpClient1, data); // 发送到192.168.10.100:8001
}
private async void ButtonSendPause_Click(object sender, EventArgs e)
{
string data = "pause";
await SendData(udpClient2, data); // 发送到192.168.10.88:777
}
private async Task SendData(UdpClient client, string message)
{
byte[] bytes = Encoding.UTF8.GetBytes(message);
IPEndPoint endpoint = client.Client.LocalEndPoint as IPEndPoint;
await client.SendAsync(bytes, bytes.Length, endpoint.Address, endpoint.Port);
}
```
阅读全文