您的位置:首页 > 移动开发 > Unity3D

Unity3D UDP 服务端例子

2016-03-21 15:08 357 查看
来源:http://forum.unity3d.com/threads/windows-udp-voice-recognition-server.172758/

// *********************************************************
// UDP SPEECH RECOGNITION
// *********************************************************
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;

public class UDP_RecoServer : MonoBehaviour
{
Thread receiveThread;
UdpClient client;
public int port = 6000; // DEFAULT UDP PORT !!!!! THE QUAKE ONE ;)
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();
Debug.Log(" MY IP : "+LocalIP);
}
}

private  void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Broadcast, port);
byte[] data = client.Receive(ref anyIP);
strReceiveUDP = Encoding.UTF8.GetString(data);
// ***********************************************************************
// Simple Debug. Must be replaced with SendMessage for example.
// ***********************************************************************
Debug.Log(strReceiveUDP);
// ***********************************************************************
}
catch (Exception err)
{
print(err.ToString());
}
}
}

public string UDPGetPacket()
{
return strReceiveUDP;
}

void OnDisable()
{
if ( receiveThread != null) receiveThread.Abort();
client.Close();
}
}
// *********************************************************
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: