c sharp與python通信
最近在學(xué)unity,想在unity調(diào)用python。因此學(xué)習(xí)了使用udp來建立通信。
python發(fā)送,c sharp接收
python代碼
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverAddressPort = ("127.0.0.1", 10086) # 5052 定義localhost與端口,當(dāng)然可以定義其他的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)
{
// 服務(wù)端
setIpAndPort Setting = new setIpAndPort("127.0.0.1", 10086);
// 1、創(chuàng)建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、接受數(shù)據(jù)
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
while (true)
{
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);
// 這個方法會把數(shù)據(jù)的來源(ip:port)放在第二個參數(shù)上。
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("data: "+message);
}
}
}
}
##############################################################
python接收,c sharp發(fā)送
python代碼
import socket # 導(dǎo)入socket庫
HOST = '127.0.0.1'
PORT = 10086
ADDR = (HOST, PORT)
BUFFSIZE = 1024 # 定義一次從socket緩沖區(qū)最多讀入1024個字節(jié)
MAX_LISTEN = 5 # 表示最多能接受的等待連接的客戶端的個數(shù)
# 創(chuàng)建UDP服務(wù)
def udpServer():
# 創(chuàng)建UPD服務(wù)端套接字
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
# 綁定地址和端口
s.bind(ADDR)
# 等待接收信息
while True:
# 接收數(shù)據(jù)和客戶端請求地址
data, address = s.recvfrom(BUFFSIZE)
if not data:
break
info = data.decode()
print(f'接收請求信息:{info}')
s.close()
if __name__ == '__main__':
udpServer()
c sharp 代碼
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Client
{
class Program
{
// 1、創(chuàng)建socket
static void Main(string[] args)
{
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2、發(fā)送數(shù)據(jù)
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10086);
string message = "客戶端發(fā)來的數(shù)據(jù)";
byte[] data = Encoding.UTF8.GetBytes(message);
while(true)
udpClient.SendTo(data, serverPoint);
Console.ReadKey();
}
}
}
每天快樂敲代碼,快樂生活

浙公網(wǎng)安備 33010602011771號