Hi,
I am trying to send data via UDP from a program written in C++ (that I use for tracking) to Unity using .Net in C#. I am kind of lost, all my attempts did not work so far and Unity crashes quite often. Here my code, could anyone tell me were I am wrong ?
Server code in C++
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int sendUDP()
{
WSADATA WSAData; //start WSAStartup()
SOCKET sock; //init socket
SOCKADDR_IN sin; //infos socket
WSAStartup(MAKEWORD(2,2), &WSAData); //enable socket use
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //create socket
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_family = AF_INET; //type socket
sin.sin_port = htons(28280); //port nb
char SendBuf[32]="From port 28280";
while(1)
{
sendto(sock, SendBuf, 32, 0, (SOCKADDR *)&sin, sizeof(sin));
}
closesocket(sock);
WSACleanup();
return 0;
}
Client code C# in Unity
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class capUDP : MonoBehaviour {
static IPEndPoint ep = new IPEndPoint(IPAddress.Any, 0);
static UdpClient udpClient = new UdpClient(28280);
static byte[] receiveBytes = new byte[32];
static string returnData = "";
void Start () {
Thread receiveThread = new Thread(ReceiveData);
receiveThread.IsBackground = true;
receiveThread.Start();
}
void Update () {
Debug.Log(returnData);
}
void ReceiveData()
{
Debug.Log("receiving...");
receiveBytes = udpClient.Receive(ref ep);
returnData = Encoding.ASCII.GetString(receiveBytes);
}
}
Thanks,
Gratoo