Sending data from Unity to Raspberry - c#

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!

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

Related

Why is my server receiving messages on a port it's not listening to? (UDP)

I have a client and server as separate applications for a unity game. This is my first time writing netcode. My code works, but the way I understand it is that it shouldn't be working.
My client is sending messages on port 7052, and listening to messages from the server on port 7062. On the other side, my server is sending messages on 7062, and listening on 7052. On line 54 and 55 of my client code, we can see the client is listening for messages on 7062 via the sendPort integer. But on the server code at line 60 we are sending the messages on 7052, which is the wrong port. The server should not be receiving these messages as it is listening for 7062, but for some reason the message is being received and outputted.
If I set the port to the correct send port, the server does not receive the message. Could someone explain why my code works like this, and if it is correct/incorrect? I want to continue scaling this for more than 1 client, but I would like to know if this solution is correct before I make this bigger. Thank you for any help you can give.
Server code:
using UnityEngine;
using TMPro;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class Network : MonoBehaviour
{
TextMeshPro console; //Reference to console in scene
Thread receiveThread; //Thread for listening to messages
UdpClient client; //Reference to client
int recvPort; //Incoming data port
string response;
// Start is called before the first frame update
void Start()
{
//Assign send and receive ports
recvPort = 7052;
//Autoresponse
response = "Server|Message Received";
}
public void Init()
{
//Start Listening
receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
Debug.Log("Server Started");
}
private void ReceiveData()
{
//Initialize client by accepting data from any IP on the assigned port
client = new UdpClient();
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.Client.Bind(new IPEndPoint(IPAddress.Any, recvPort));
while (true)
{
try
{
//Check for data from any IP on assigned listening port
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, recvPort);
byte[] data = client.Receive(ref anyIP);
//Convert byte array message to string and output it
string text = Encoding.UTF8.GetString(data);
Debug.Log(text + " Received on port" + anyIP.Port);
//Let the client know the data was received
byte[] resp = Encoding.UTF8.GetBytes(response);
client.Send(resp, resp.Length, anyIP);
}
catch (Exception err)
{
//Output socket error
Debug.Log(err);
}
}
}
}
Client code:
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class Client : MonoBehaviour
{
Thread receiveThread; //Thread for listening to messages
IPEndPoint remoteEndPoint; //Remote endpoint for server
UdpClient serverRecv; //udpclient for server??
//Connection info
string IP;
int recvPort;
int sendPort;
// Start is called before the first frame update
void Start()
{
//Assign connection info to server and inbound/outbound ports
IP = "127.0.0.1";
recvPort = 7062;
sendPort = 7052;
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);
//Bind server to socket and start listening
serverRecv = new UdpClient();
serverRecv.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
serverRecv.Client.Bind(new IPEndPoint(IPAddress.Any, recvPort));
StartListen();
}
//Thread listening for messages
public void StartListen()
{
receiveThread = new Thread(
new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveData()
{
while (true)
{
try
{
//Check for data from server on assigned port
IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse(IP), recvPort);
byte[] data = serverRecv.Receive(ref serverIP);
//Convert byte array message to string and output it
string text = Encoding.UTF8.GetString(data);
Debug.Log(text + " Received on port" + serverIP.Port);
}
catch (Exception err)
{
//Output socket error
Debug.Log(err);
}
}
}
public void LogIn()
{
sendString("Client|Hi! I would like to log in");
}
private void sendString(string message)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
serverRecv.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err);
}
}
}
You never set a port that the server sends messages to the client. The server gets the information but the client never recevies anything because the server doesn't send info on the port.

C# - Cannot connect my Socket Server

Good afternoon dear community,
I am currently working on a Arduino + Unity project where I am supposed to build an Arduino control through Unity. For that, I have set my Arduino and connected to wifi.
I built a Socket Server with C#. The problem is that: I am able to connect to this Socket Server through a Node.js Socket Client, however to check if my Arduino setup is broken, I have built a Node.js Socket Server and was able to connect my Node.js Socket server succesfully through Arduino. (The only reason I am using Node.js here is that because I am more fluent on that platform so I am able to check what is wrong, so final project does not have any Node.js.) So;
Node.js Client -> Unity C# Server (Works)
Arduino Client -> Node.js Server (Works) (Below is Arduino output)
AT+CIPSTART=3,"TCP","192.168.1.67",1234
OK
Linked
Arduino Client -> Unity C# Server (Does not work) (Below is Arduino output)
AT+CIPSTART=3,"TCP","192.168.1.67",1234
ERROR
Unlink
Below I am putting my all C#, Node.js and Arduino codes. I don`t think that there is an Arduino hardware issue here, but don·t understand why I cannot connect my
Unity Socket Server.
using System;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using UnityEngine;
public class SocketScript : MonoBehaviour {
Thread tcpListenerThread;
void Start()
{
tcpListenerThread = new Thread(() => ListenForMessages(1234));
tcpListenerThread.Start();
}
public void ListenForMessages(int port)
{
TcpListener server = null;
try
{
IPAddress localAddr = IPAddress.Parse("192.168.1.67");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new byte[256];
String data = null;
while(true)
{
Debug.Log("Waiting for connection.");
using (TcpClient client = server.AcceptTcpClient())
{
Debug.Log("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
// As long as there is something in the stream:
while((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Debug.Log(String.Format("Received: {0}", data));
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Debug.Log(String.Format("Sent: {0}", data));
}
}
}
} catch (SocketException e)
{
Debug.LogError(String.Format("SocketException: {0}", e));
} finally
{
server.Stop();
}
}
}
Node.js Client:
var net = require('net');
var HOST = '192.168.1.67';
var PORT = 1234;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('Client connected to: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('Hello World!');
});
client.on('data', function(data) {
console.log('Client received: ' + data);
if (data.toString().endsWith('exit')) {
client.destroy();
}
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Client closed');
});
client.on('error', function(err) {
console.error(err);
});
Node.js Server:
var net = require('net');
// Configuration parameters
var HOST = '192.168.1.67';
var PORT = 1234;
// Create Server instance
var server = net.createServer(onClientConnected);
server.listen(PORT, HOST, function() {
console.log('server listening on %j', server.address());
});
function onClientConnected(sock) {
var remoteAddress = sock.remoteAddress + ':' + sock.remotePort;
console.log('new client connected: %s', remoteAddress);
sock.on('data', function(data) {
console.log('%s Says: %s', remoteAddress, data);
sock.write(data);
sock.write(' exit');
});
sock.on('close', function () {
console.log('connection from %s closed', remoteAddress);
});
sock.on('error', function (err) {
console.log('Connection %s error: %s', remoteAddress, err.message);
});
};

Unity and UDP MulticastGroup

I'm trying to listen in on a host that's sending over UDP using MultiCastGroup. In Unity the client starts but no message is ever received, but if I take the exact same code and drop it into a console application it works and I see the host's messages.
Here's what I've got:
public class UDPListener : MonoBehaviour
{
IPEndPoint ip;
private int port = 20000;
private IPAddress group_address = IPAddress.Parse("233.255.255.255");
private UdpClient client;
string data;
private void Start()
{
StartClient();
}
void StartClient()
{
Debug.Log("Starting Client");
ip = new IPEndPoint(IPAddress.Any, port);
client = new UdpClient(ip);
client.JoinMulticastGroup(group_address);
client.BeginReceive(new AsyncCallback(ReceiveServerInfo), null);
}
void ReceiveServerInfo(IAsyncResult result)
{
byte[] receivedBytes = client.EndReceive(result, ref ip);
data = Encoding.ASCII.GetString(receivedBytes);
if (String.IsNullOrEmpty(data))
{
Debug.Log("No data received");
}
else
{
Debug.Log(data);
}
client.BeginReceive(new AsyncCallback(ReceiveServerInfo), null);
}
}
I've also had the same result using client.Receive (works in console application but not in Unity) so I'm wondering if there's maybe some Unity setting I'm missing?
Nevermind, Windows update had turned my firewall back on which was blocking Unity :]

TCP Connexion between Xamarin.Android and SDL_Net

I'm trying to establish a TCP connexion between a C# Xamarin Android app and a C++ app on a Raspberry pi.
On the C# client side, I'm using the TcpClient client from System.Net.Sockets :
// C#
static public bool Connect(string IP, string port)
{
bool _connected = false;
try
{
client = new TcpClient();
IPAddress _ip = IPAddress.Parse(IP);
int _port = int.Parse(port);
client.Connect(_ip, _port);
_connected = true;
}
catch
{
_connected = false;
}
return _connected;
}
This is a pretty straight forward use of the TcpClient class as you can see.
On the server side, using SDL_Net (1.2), here is my socket init :
// C++
string mNet::Resolve()
{
socketSet = SDLNet_AllocSocketSet(2);
if(socketSet == NULL)
return "Could not allocate socket set : " + string(SDLNet_GetError());
if(SDLNet_ResolveHost(&serverIP, NULL, Prefs::NET_PORT) == -1)
return "Could not resolve server host : " + string(SDLNet_GetError());
serverSocket = SDLNet_TCP_Open(&serverIP);
if(!serverSocket)
return "Could not create server socket : " + string(SDLNet_GetError());
SDLNet_TCP_AddSocket(socketSet, serverSocket);
return "OK";
}
and here is a dummy listener for testing :
// C++
void mNet::Update()
{
int serverSocketActivity = SDLNet_SocketReady(serverSocket);
if (serverSocketActivity != 0)
{
if(!ClientConnected) // new connection
{
clientSocket = SDLNet_TCP_Accept(serverSocket);
SDLNet_TCP_AddSocket(socketSet, clientSocket);
ClientConnected = true;
SendToClient("1");
Logger::Log("Client connected !");
}
else // server busy
{
SendToClient("0", true);
Logger::Log("Client refused !");
}
}
}
I get no error from the initialization, and when I run a netstat -an | grep tcp command on the raspberry, I can see the port i'm using (1234) opened.
But when I try to connect from the android emulator, it seems that nothing is happening server side (no socket activity).
IP & ports are matching.
I'm not really used to networking, so is there something I'm doing wrong here ?
Additional info :
Targeting Android 6
RaspberryPi is running UbunutuMate
Networking C# class : https://github.com/arqtiq/RemotePlayerPi/blob/master/App/Network.cs
Networking C++ class : https://github.com/arqtiq/RemotePlayerPi/blob/master/Server/src/mNet.cpp
Thanks !

C# UDP Socket client and server

My first question here. I am new to this kind of programming, and i've only programmed .NET web sites and forms.
Now, the company I work at, asks me to make an ActiveX component, that listens to UDP messages, and turns them into events.
The UDP msgs are send from Avaya system, so i was told that to test my ActiveX, at first I need to create an app, that only sends UDP (only one button that sends pre-defined UDP string). And then create listener socket, ordinary C# app, that will get those transmitted UDP string from the tests app. Both apps will work on the same machine.
Later, when i get this working, i need to make the listener an ActiveX component, but first things first.
I need to know if there are any good tutorials about this, and any idea on how to start? I am sorry for my ignorance, but i am really new on this and i don't really have any time to learn this since it has to be done in 2 weeks.
Thanks in advance.
edit: I managed to create 2 simple console applications, and was sending UDP messages between them successfully. The sender will be only for testing, and now I need to re-make my receiver to get the UDP message and 'translate' it to events. And lastly, to make it an ActiveX control...
Simple server and client:
public struct Received
{
public IPEndPoint Sender;
public string Message;
}
abstract class UdpBase
{
protected UdpClient Client;
protected UdpBase()
{
Client = new UdpClient();
}
public async Task<Received> Receive()
{
var result = await Client.ReceiveAsync();
return new Received()
{
Message = Encoding.ASCII.GetString(result.Buffer, 0, result.Buffer.Length),
Sender = result.RemoteEndPoint
};
}
}
//Server
class UdpListener : UdpBase
{
private IPEndPoint _listenOn;
public UdpListener() : this(new IPEndPoint(IPAddress.Any,32123))
{
}
public UdpListener(IPEndPoint endpoint)
{
_listenOn = endpoint;
Client = new UdpClient(_listenOn);
}
public void Reply(string message,IPEndPoint endpoint)
{
var datagram = Encoding.ASCII.GetBytes(message);
Client.Send(datagram, datagram.Length,endpoint);
}
}
//Client
class UdpUser : UdpBase
{
private UdpUser(){}
public static UdpUser ConnectTo(string hostname, int port)
{
var connection = new UdpUser();
connection.Client.Connect(hostname, port);
return connection;
}
public void Send(string message)
{
var datagram = Encoding.ASCII.GetBytes(message);
Client.Send(datagram, datagram.Length);
}
}
class Program
{
static void Main(string[] args)
{
//create a new server
var server = new UdpListener();
//start listening for messages and copy the messages back to the client
Task.Factory.StartNew(async () => {
while (true)
{
var received = await server.Receive();
server.Reply("copy " + received.Message, received.Sender);
if (received.Message == "quit")
break;
}
});
//create a new client
var client = UdpUser.ConnectTo("127.0.0.1", 32123);
//wait for reply messages from server and send them to console
Task.Factory.StartNew(async () => {
while (true)
{
try
{
var received = await client.Receive();
Console.WriteLine(received.Message);
if (received.Message.Contains("quit"))
break;
}
catch (Exception ex)
{
Debug.Write(ex);
}
}
});
//type ahead :-)
string read;
do
{
read = Console.ReadLine();
client.Send(read);
} while (read != "quit");
}
}
Simple server and client:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
// Create UDP client
int receiverPort = 20000;
UdpClient receiver = new UdpClient(receiverPort);
// Display some information
Console.WriteLine("Starting Upd receiving on port: " + receiverPort);
Console.WriteLine("Press any key to quit.");
Console.WriteLine("-------------------------------\n");
// Start async receiving
receiver.BeginReceive(DataReceived, receiver);
// Send some test messages
using (UdpClient sender1 = new UdpClient(19999))
sender1.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);
using (UdpClient sender2 = new UdpClient(20001))
sender2.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);
// Wait for any key to terminate application
Console.ReadKey();
}
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
// Convert data to ASCII and print in console
string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine);
// Restart listening for udp data packages
c.BeginReceive(DataReceived, ar.AsyncState);
}
}
Server
public void serverThread()
{
UdpClient udpClient = new UdpClient(8080);
while(true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
lbConnections.Items.Add(RemoteIpEndPoint.Address.ToString()
+ ":" + returnData.ToString());
}
}
And initialize the thread
private void Form1_Load(object sender, System.EventArgs e)
{
Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
thdUDPServer.Start();
}
Client
private void button1_Click(object sender, System.EventArgs e)
{
UdpClient udpClient = new UdpClient();
udpClient.Connect(txtbHost.Text, 8080);
Byte[] senddata = Encoding.ASCII.GetBytes("Hello World");
udpClient.Send(senddata, senddata.Length);
}
Insert it to button command.
Source: http://technotif.com/creating-simple-udp-server-client-transfer-data-using-c-vb-net/

Categories

Resources