我正在尝试利用Socket连接将PyCharm中我的python脚本(Python 3.6.3)中的数据发送到Unity3D中的C#脚本。
非常类似于:https://www.youtube.com/watch?v=eI3YRluluR4
在documentation之后,以下脚本应该可以正常运行
Python脚本:
import socket
host, port = "127.0.0.1", 25001
data = "hello"
# SOCK_STREAM means a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((host, port))
sock.sendall(data.encode("utf-8"))
data = sock.recv(1024).decode("utf-8")
print(data)
finally:
sock.close()
C#脚本:
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using System.Threading;
public class networkCon : MonoBehaviour
{
Thread mThread;
public string connectionIP = "127.0.0.1";
public int connectionPort = 25001;
IPAddress localAdd;
TcpListener listener;
TcpClient client;
Vector3 pos = Vector3.zero;
bool running;
private void Start()
{
ThreadStart ts = new ThreadStart(GetInfo);
mThread = new Thread(ts);
mThread.Start();
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new System.Exception("No network adapters with an IPv4 address in the system!");
}
void GetInfo()
{
localAdd = IPAddress.Parse(connectionIP);
listener = new TcpListener(IPAddress.Any, connectionPort);
listener.Start();
client = listener.AcceptTcpClient();
running = true;
while (running)
{
Connection();
}
listener.Stop();
}
void Connection()
{
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (dataReceived != null)
{
if (dataReceived == "stop")
{
running = false;
}
else
{
pos = 10f * StringToVector3(dataReceived);
print("moved");
nwStream.Write(buffer, 0, bytesRead);
}
}
}
但是,在运行Python脚本时,我会继续:
第11行,在 sock.connect((主机,端口)) ConnectionRefusedError:[WinError 10061]无法建立连接,因为目标计算机主动拒绝它。
类似的question有这个答案,但我不认为这适用于我的情况。 PyCharm编辑器可能需要更改一些设置吗?
我该如何解决这个问题?