UDP sous Unity

Pour les scripts écrits en C#
Règles du forum
Merci de respecter la NOMENCLATURE suivante pour vos TITRES de messages :

Commencez par le niveau de vos scripts
DB = Débutant
MY = Moyen
CF = Confirmé

Puis le domaine d'application
-RS = Réseau
-AL = Algorithmie

Exemple :

[DB-RS] Mouvement perso multijoueur
Avatar de l’utilisateur
ZJP
Messages : 5748
Inscription : 15 Déc 2009 06:00

UDP sous Unity

Message par ZJP » 30 Sep 2010 20:01

Salut,

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 :lol: 8-)
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();
	}
}
La réception

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

Dernière édition par ZJP le 03 Déc 2010 05:51, édité 3 fois.

Avatar de l’utilisateur
spoke2018
Messages : 6
Inscription : 28 Sep 2010 19:40

Re: UDP sous Unity

Message par spoke2018 » 05 Oct 2010 22:58

merci ca peux toujours servir :D
Monsieur Spoke !

Blitz3D » PureBasic » 3DGS » Unity3D » de plus en plus fou !!!

Avatar de l’utilisateur
ZJP
Messages : 5748
Inscription : 15 Déc 2009 06:00

Re: UDP sous Unity

Message par ZJP » 05 Août 2011 02:49

Salut,

Petite mise à jour. Version 3.x. Test sans soucis entre Desktop et Android.

Receive dans un thread. 8-)

Code : Tout sélectionner

using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net.NetworkInformation;

public class UDPReceive : MonoBehaviour {
	Thread receiveThread; 
	UdpClient client; 
	public int port = 26000;  
	string strReceiveUDP="";
        string LocalIP = String.Empty;
	string hostname;

       public void Start()
	{
		Application.runInBackground = true;
		init();	
	}
	// init
	private void init()
	{
		receiveThread = new Thread( new ThreadStart(ReceiveData));
		receiveThread.IsBackground = true;
		receiveThread.Start();
		hostname = Dns.GetHostName();
		IPAddress[] ips = Dns.GetHostAddresses(hostname);
		if (ips.Length > 0)
		{
			LocalIP = ips[0].ToString();
		}
	}

	void OnGUI()
	{
		Rect rectObj=new Rect(10,10,400,200);
		GUIStyle style = new GUIStyle();
		style.alignment = TextAnchor.UpperLeft;
		GUI.Box(rectObj,hostname+" MY IP : "+LocalIP+" : "+strReceiveUDP,style);
	}

	private  void ReceiveData() 
	{
		client = new UdpClient(port);
		while (true) 
		{
			try 
			{
				IPEndPoint anyIP = new IPEndPoint(IPAddress.Broadcast, port);
				//IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
				byte[] data = client.Receive(ref anyIP);
				string text = Encoding.UTF8.GetString(data);
				strReceiveUDP = text;
				//Debug.Log(strReceiveUDP);
			}
			catch (Exception err) 
			{
				print(err.ToString());
			}
		}
	}

       public string UDPGetPacket()
	{
            return strReceiveUDP;
	}

	void OnDisable()
	{
		if ( receiveThread!= null)	receiveThread.Abort();
		client.Close();
	}
}
Send

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 = "192.168.1.10"; // default local
	public int port = 26000;  
	IPEndPoint remoteEndPoint;
	UdpClient client;
	string strMessage="";

	public void Start()
	{
		init();	
        }

       void OnGUI()
	{
		Rect rectObj=new Rect(40,120,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,160,140,40),strMessage);
		if (GUI.Button(new Rect(180,160,80,40),"Send"))
		{
			sendString(strMessage);
		}		
	}

	public void init()
	{
		remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, port);
		//remoteEndPoint = new IPEndPoint(IPAddress.Any, port);
		//remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
		client = new UdpClient();
	}

	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();
	}
}
Dernière édition par ZJP le 06 Sep 2011 18:47, édité 2 fois.

Avatar de l’utilisateur
Freelax
Messages : 1595
Inscription : 30 Déc 2009 23:02
Localisation : Niort
Contact :

Re: UDP sous Unity

Message par Freelax » 05 Août 2011 04:16

yes ! merci :D
Image

cahen
Messages : 1
Inscription : 04 Août 2010 11:05

Re: UDP sous Unity

Message par cahen » 04 Avr 2012 20:41

Bonjour,
J'ai essayé UDPSend, mais ne reçois pas la donnée, seulement la référence du packet :
"FullPacket 6 453832880"
ais-je oublié quelque chose ?
Merci
RC

Avatar de l’utilisateur
A_cube
Messages : 63
Inscription : 08 Juil 2011 08:50

Re: UDP sous Unity

Message par A_cube » 02 Sep 2014 09:26

Avec l'UDP, peut-on envoyer une RenderTexture à une autre application ?

Exemple : Le master a le terrain et une caméra pour celui qui l'utilise. Il dispose d'une deuxième caméra (qu'il ne voit pas) dont il envoie ce qu'elle voit directement au client (comme ça le client n'a pas à avoir tous les assets, il ne reçoit que la RenderTexture.)

Image
Cherche à faire un blog pour mes projets, des suggestions ? Merci ;) || WIP (Aeourant) en préparation ... :D

Avatar de l’utilisateur
artemisart
Messages : 1893
Inscription : 21 Juin 2011 19:51
Localisation : Centre
Contact :

Re: UDP sous Unity

Message par artemisart » 02 Sep 2014 10:21

RenderTexture, je sais pas, mais une Texture/Texture2D forcément ;)
Par contre niveau bande passante envoyer du full hd à mini 30fps ça fait mal :D, tu peux pas streamer les assets ?

Avatar de l’utilisateur
A_cube
Messages : 63
Inscription : 08 Juil 2011 08:50

Re: UDP sous Unity

Message par A_cube » 02 Sep 2014 10:26

Si c'est possible.

Mais c'était pour savoir si cette idée était réalisable. Avec le client qui a juste le retour vidéo et quand il fait une actions, elle est envoyée au master.

Je ne pensais pas forcément à du full hd, mais plutôt à une résolution de tablette (mais qui sont de plus en plus grande c'est sur)

Surtout que maintenant on peut encoder directement en jpeg
Cherche à faire un blog pour mes projets, des suggestions ? Merci ;) || WIP (Aeourant) en préparation ... :D

Avatar de l’utilisateur
artemisart
Messages : 1893
Inscription : 21 Juin 2011 19:51
Localisation : Centre
Contact :

Re: UDP sous Unity

Message par artemisart » 02 Sep 2014 11:30

Ça dépend quelles tablettes mais un bon nombre sont en hd/fhd !
Le jpeg est assez lourd pour de la vidéo (et j'ai lu que l'implémentation de Unity était assez lente), du streaming h264 serait mieux mais c'est moins facile à implémenter.

sawi
Messages : 3
Inscription : 06 Avr 2015 20:34

Re: UDP sous Unity

Message par sawi » 06 Avr 2015 20:40

bonsoir à tous
j'ai bien utilisé le code proposé par ZJP , j'ai utiliser la partie 'send' pour une tablette et j'ai essayé de faire communiquer cette tablette avec mon pc mais je reçois rien. j'arrive pas à connaitre ou se trouve le problème :cry: .
pouvez vous m'aider j'ai vraiment besoin de cette partie pour mon projet !
merci a tous

Répondre

Revenir vers « (C#) CSharp »