最近在学unity,想在unity调用python。因此学习了使用udp来建立通信。
python发送,c sharp接收
python代码
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverAddressPort = ("127.0.0.1", 10086) # 5052 定义localhost与端口,当然可以定义其他的host
count = 0
while True:
sock.sendto(str.encode(str(count)), serverAddressPort)
count += 1
time.sleep(1)
c sharp代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Client
{
class setIpAndPort
{
private string ip;
private int port;
public void setIp(string Ip)
{
ip = Ip;
}
public void setPort(int Port)
{
port = Port;
}
public setIpAndPort(string Ip, int Port)
{
ip = Ip;
port = Port;
}
public string getIp()
{
return ip;
}
public int getPort()
{
return port;
}
}
class Program
{
static void Main(string[] args)
{
// 服务端
setIpAndPort Setting = new setIpAndPort("127.0.0.1", 10086);
// 1、创建Udp Socket
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2、绑定ip跟端口号
udpServer.Bind(new IPEndPoint(IPAddress.Parse(Setting.getIp()), Setting.getPort()));
// 3、接受数据
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
while (true)
{
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);
// 这个方法会把数据的来源(ip:port)放在第二个参数上。
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("data: "+message);
}
}
}
}
标签:string,using,python,ip,通信,System,new,sharp
From: https://www.cnblogs.com/crazyMint/p/17311315.html