unity udp广播 android,unity_Socket_UDP广播协议的接收发送(客户端模块)

  • Post author:
  • Post category:其他


usingSystem;usingSystem.Text;usingSystem.Threading;usingUnityEngine;usingSystem.Net.Sockets;usingSystem.Net;usingSystem.Collections.Generic;//usingSystem.Xml;public classLighthouse : MonoBehaviour

{private byte[] data;private stringError_Message;privateThread thread;privateEndPoint ep;private bool IsStop = false;privateSocket socket;private int udpPort = 9090;public staticLighthouse instance;//消息回调

private static string m_callMessage = string.Empty;private bool m_isTCP = true;private voidAwake()

{if (instance == null)

{

instance= this;//

//GetSeverIP();//DontDestroyOnLoad(gameObject);

}//else//{//Destroy(gameObject);//}// m_isTCP = true;

}private voidUpdate()

{if(m_isTCP)

{if (!string.IsNullOrEmpty(m_callMessage))

{this.SendUDP_SceneInfo();//建立TCP连接

Client._Instance.StartConnect(this.Analyse_XMLIP());// m_isTCP = false;

}

}

}public voidGetSeverIP()

{try{

socket= newSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

ep= newIPEndPoint(IPAddress.Any, udpPort);

socket.Bind(ep);

data= new byte[1024];

thread= newThread(Receive);

thread.IsBackground= true;

thread.Start();

}catch(Exception e)

{

Debug.LogError(“错误信息:” +e.Message);

}

}public voidStopReceive()

{

IsStop= true;

thread.Abort();

}private voidReceive()

{while (!IsStop)

{if (socket.Available <= 0) continue;int recv = socket.ReceiveFrom(data, refep);string msg = Encoding.ASCII.GetString(data, 0, recv);//Debug.Log(“接收消息:” + msg);

Debug.Log(“[UDP+接收消息]” +msg);// m_callMessage = string.Empty;

m_callMessage=msg;//测试//if(recv > 0)//{//Send(msg);//}//Thread.Sleep(100);

}

}public void Send(stringmsg)

{//msg = “客户端消息:66666666666”;

Debug.Log(“[UPD+发送消息]” +msg);

data=Encoding.UTF8.GetBytes(msg);try{

socket.SendTo(data, ep);

}catch(Exception ex)

{

Debug.Log(“错误信息” +ex.Message);

}

}public voidOnApplicationQuit()

{if (socket != null)

{

socket.Shutdown(SocketShutdown.Both);

socket.Close();

}

IsStop= true;

thread.Abort();

}//信息_ID_场景_0或回调信息//发送UDP数据

private voidSendUDP_SceneInfo()

{

UDPMessage um= new UDPMessage(MessageType.Register,0,”故宫”,”0″);//Send(um.ToString());

}//解析xml中的ip地址

private stringAnalyse_XMLIP()

{// string strUrl = “D:/LUYOU_File/Msg/addressInfo.xml”;

XmlDocument xmlDoc= newXmlDocument();

xmlDoc.Load(strUrl);// if (xmlDoc!=null)

{

XmlElement node=(XmlElement)xmlDoc.SelectSingleNode(“address/ip”);returnnode.InnerText.Trim();

}return null;

}

}public classUDPMessage {privateMessageType msgType;private intPlayerID;private stringstrSceneName;private stringstrCallMessage;public UDPMessage(MessageType type,int id,string sceneName,stringcallMessage)

{this.msgType =type;this.PlayerID =id;this.strSceneName =sceneName;this.strCallMessage =callMessage;

}public override stringToString()

{return string.Format(“{0}_{1}_{2}_{3}#”,(int)msgType,PlayerID,strSceneName,strCallMessage);

}

}