gpt4 book ai didi

c# - 将数据从 Unity 发送到 Raspberry

转载 作者:行者123 更新时间:2023-12-01 03:47:10 26 4
gpt4 key购买 nike

我正在尝试将数据从 Unity 发送到 Raspberry Pi。我已成功连接它们,但无法传递任何数据,请帮忙。

这是我在 Raspberry 端使用的代码

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 Answers[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();
}

Raspberry Pi 上的 Python:

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

关于c# - 将数据从 Unity 发送到 Raspberry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38816660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com