将数据从Unity发送到Raspberry
本文关键字:Raspberry Unity 数据 | 更新日期: 2023-09-27 18:01:22
我正试图将数据从Unity发送到树莓派。我已成功连接,但无法传递任何数据,请帮助。
这是我在树莓端使用的代码
import socket
backlog=1
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("169.254.242.100",50001))
s.listen(backlog)
try:
print ( "is waiting")
client, address = s.accept()
while 1:
data = client.recv(size)
if data:
tabela = data
print ( "sends data")
print (tabela[0])
client.send(data)
except:
print("closing socket")
client.close()
s.close()
这个是我在Unity中使用的
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
public class UnityToRaspberry : MonoBehaviour {
public string IP = "169.254.242.100"; //
public int Port = 50001;
public byte[] dane = System.Text.Encoding.ASCII.GetBytes("Hello");
public Socket client;
void Start(){
//dane [0] = 1;
client = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect (IP, Port);
if (client.Connected) {
Debug.Log ("Connected");
}
client.Send (dane);
}
void OnApplicationQuit(){
client.Close();
}
}
谢谢!
我打赌你已经非常接近了!我使用了你的代码加上Unity答案[1]中的一个例子。这就是我必须通过tcp套接字在Mac OSX Sierra上的Unity 5.5.0f3和Raspberry Pi 3 Model B之间建立连接和传输数据的方法。
在统一:
void setupSocket()
{
s.socketReady = false;
s.host = "192.20.20.2";
s.port = 50001;
try {
s.socket = new TcpClient(s.host, s.port);
s.stream = s.socket.GetStream();
s.writer = new StreamWriter(s.stream);
s.reader = new StreamReader(s.stream);
s.socketReady = true;
}
catch (Exception e) {
Debug.Log("Socket error:" + e);
}
}
void Update()
{
s.writer.Write("Hello Pi!");
s.writer.Flush();
}
Python on the Pi:
import socket
backlog = 1
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.20.20.2', 50001))
s.listen(backlog)
try:
print ("is waiting")
client, address = s.accept()
while 1:
data = client.recv(size)
if data:
print (data)
except:
print("closing socket")
client.close()
s.close()
来源:http://answers.unity3d.com/questions/601572/unity-talking-to-arduino-via-wifiethernet.html
https://docs.python.org/2/library/socket.html