1

I'm trying to send data from Unity to Raspberry Pi. I have succesfully connected them but I can't pass any data please help.

This is code that I use on the Raspberry side

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()

and this is the one I use in 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();
}



}

Thank You!

1 Answer 1

3

I bet you were super close! I've used your code plus an example from the Unity Answers[1]. This is what I have to establish a connection and transfer data between Unity 5.5.0f3 on Mac OSX Sierra and a Raspberry Pi 3 Model B via tcp sockets.

In Unity:

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()

sources: http://answers.unity3d.com/questions/601572/unity-talking-to-arduino-via-wifiethernet.html

https://docs.python.org/2/library/socket.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.