【问题标题】:Sending data from Unity to Raspberry从 Unity 向 Raspberry 发送数据
【发布时间】:2016-12-13 11:42:54
【问题描述】:

我正在尝试将数据从 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();
}



}

谢谢!

【问题讨论】:

    标签: c# python unity3d


    【解决方案1】:

    我敢打赌你是超级接近!我使用了您的代码以及 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();
    }
    

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2021-03-27
      相关资源
      最近更新 更多