Après avoir bien galéré pour établir des communications UDP sous Unity, voici les sources (résultats combinées de recherches, bidouilles...) qui fonctionnent. Essayées entre Unity, Blitz3D,VB6, C++. C'est donc du pur générique, standard, de base etc... passe partout
Ca fonctionne aussi entre le mode WebPlayer et le Standalone. Un moyen d'échanger des données entre les différents "builds"
JP
L'émission
Code : Tout sélectionner
//
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDPSend : MonoBehaviour
{
public string IP = "127.0.0.1"; // default local
public int port = 26000;
IPEndPoint remoteEndPoint;
UdpClient client;
string strMessage="";
public void Start()
{
init();
}
void OnGUI()
{
Rect rectObj=new Rect(40,380,200,400);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
GUI.Box(rectObj,"UDPSendData\n IP : "+IP+" Port : "+port,style);
//
strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
if (GUI.Button(new Rect(190,420,40,20),"Send"))
{
sendString(strMessage+"\n");
}
}
// init
public void init()
{
IP="127.0.0.1";
port=26000; // quake port ;)
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
//remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, port); // toute machine
client = new UdpClient();
}
// sendData
private void sendString(string message)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
void OnDisable()
{
if ( client!= null) client.Close();
}
}
Code : Tout sélectionner
/*
*/
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDPReceive : MonoBehaviour {
// receiving Thread
Thread receiveThread;
// udpclient object
UdpClient client;
public string IP = "127.0.0.1"; // default local
public int port = 26000;
public GUIText ecriture;
string strReceiveUDP="";
public void Start()
{
Application.runInBackground = true;
init();
}
// init
private void init()
{
// define port
port = 26000;
receiveThread = new Thread( new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
// receive thread
private void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.UTF8.GetString(data);
strReceiveUDP = text;
ecriture.text="Reception : "+strReceiveUDP;
}
catch (Exception err)
{
print(err.ToString());
}
receiveThread.Sleep(20);
}
}
public string UDPGetPacket()
{
return strReceiveUDP;
}
void OnDisable()
{
if ( receiveThread!= null) receiveThread.Abort();
client.Close();
}
}