利用scoket的udp协议写一个python与c#的通信协议
时间: 2024-03-03 19:48:24 浏览: 16
下面是一个简单的UDP协议的Python与C#通信示例:
Python端代码:
```python
import socket
# 创建UDP Socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口
udp_socket.bind(('127.0.0.1', 8888))
while True:
# 接收数据
data, addr = udp_socket.recvfrom(1024)
print('Received from C#:', data.decode())
# 发送数据
msg = input('Please input message to C#: ')
udp_socket.sendto(msg.encode(), addr)
```
C#端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
// 创建UDP Socket
var udpSocket = new UdpClient(8888);
while (true)
{
// 接收数据
var remoteEP = new IPEndPoint(IPAddress.Any, 0);
var data = udpSocket.Receive(ref remoteEP);
Console.WriteLine($"Received from Python: {Encoding.UTF8.GetString(data)}");
// 发送数据
Console.Write("Please input message to Python: ");
var msg = Console.ReadLine();
var sendBytes = Encoding.UTF8.GetBytes(msg);
udpSocket.Send(sendBytes, sendBytes.Length, remoteEP);
}
}
}
```
运行Python端代码后,再运行C#端代码,两个程序就可以互相发送数据了。需要注意的是,UDP协议是无连接的,因此发送的数据可能会丢失或乱序,需要在应用层进行相应的处理。