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

标签 c# python unity-game-engine

我正在尝试将数据从 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/

相关文章:

python - 在值为单个整数的字典中将它们更改为列表

java - AndroidJavaProxy 不是一个接口(interface)

android - 在 Unity Android 中使用 assetbundle 和流媒体资源文件夹

c# - 使用 C# 中的 Touchatag 阅读器?

c# - 从从 api 填充的 ListView 行单击中提取数据

c# - 在 SQL Server 中创建 ASCII SHA-512 哈希

python正则表达式强制换行

python - 为什么这个简单的条件表达式不起作用?

c# - 如何向 EditorGUILayout.TextArea 添加自动换行?

c# - Windows 窗体设计 View 的底部空间是什么?