所以昨天我把所有这些都用在了与Unity交谈的Raspberry Pi上(Pi上的Python 2.7,Unity 2017),然后存储卡失败了,我不得不建立一个新的。新安装是Python 3.5和Unity一样。我认为我编写的代码大致相同但是通过故障排除它有点改变(打印语句改变等为3.5)。无论哪种方式,我都会在Unity方面收到错误,说连接方在一段时间后没有正确响应。我已经从PC和其他计算机上ping了IP和套接字,它可以访问,但只有Unity应用程序才能与Pi服务器通信。有人能看到我在我的代码中搞砸了吗?在PC上禁用防火墙,并且Pi的IP /端口地址是正确的。
Raspberry Pi上的Python
import socket
import sys
backlog = 1
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.3.232', 12345))
s.listen(1)
while True:
print ('waiting for a connection')
connection, client_address = s.accept()
try:
print ('connection from', client_address)
while True:
data = connection.recv(16)
print ('received "%s"' % data)
if data:
print ('sending data back to the client')
connection.sendall(data)
else:
print ('no more data from', client_address)
break
finally:
print("closing socket")
cient.close()
s.close()
C#on Unity
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;
public class ClientSocket : MonoBehaviour {
bool socketReady = false;
TcpClient mySocket;
public NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
public String Host = "192.168.3.232";
public Int32 Port = 12345;
void Start() {
setupSocket ();
}
public void setupSocket() { // Socket setup here
try {
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e) {
Debug.Log("Socket error:" + e); // catch any exceptions
}
}
Unity控制台出错: 套接字错误:System.Net.Sockets.SocketException:连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接主机无法响应而建立连接失败。
答案 0 :(得分:0)
Raspberry Pi上的防火墙可能仍然存在。检查你的iptables。 如果你在Raspberry Pi上的python中创建一个小的sockettest应用程序,你可以测试一下。
答案 1 :(得分:0)
@科林。我将您的Python代码复制并粘贴到了Raspberry Pi上运行的Python 2.7.9中,并将其粘贴到了PC上运行的Unity中的Client Socket中,并且工作正常。只需更改IP地址即可,一切正常。我知道这是一个较晚的回复,但可能会对其他人有所帮助。