// Author: smilelance
// From: http://blog.csdn.net/smilelance
Using unityengine;
Using system. collections;
Using system. net;
Using system. net. Sockets;
Using system. text;
Using system;
Public class udpconnection {
Private Static udpconnection instance;
Private const system. int3serverport = 8320;
Private const string serveraddress = "10.1.13.157 ";
Udpclient;
Private udpconnection ()
{
}
Public static udpconnection getinstance ()
{
If (instance = NULL ){
Instance = new udpconnection ();
}
Return instance;
}
Public void startudpconnection (){
Udpclient = new udpclient ();
Udpclient. Connect (serveraddress, SERVERPORT );
// Ipendpoint object will allow us to read into rams sent from any source.
Ipendpoint remoteipendpoint = new ipendpoint (IPaddress. Any, 0 );
// Sends a message to the host to which you have connected.
Byte [] sendbytes = encoding. utf8.getbytes ("client start online? ");
// Asyncsend (sendbytes );
// Udpclient. Send (sendbytes, sendbytes. Length );
Asyncreceive ();
}
// Send data
Public void asyncsend (byte [] data ){
If (data. length> 0 ){
// Debug. Log ("sending:" + encoding. utf8.getstring (data ));
// Udpclient. Send (data, data. length, ipep );
Udpclient. beginsend (data, data. length, new asynccallback (senddatacallback), null );
}
}
// Receive data
Public void asyncreceive (){
Udpclient. beginreceive (New asynccallback (receivedatacallback), null );
}
// Send data callback
Public static bool messagesent = false;
Private void senddatacallback (iasyncresult AR)
{
// Udpclient u = (udpclient) Ar. asyncstate;
// Print (U. endsend (AR ));
// U. endsend (AR );
// Debug. Log ("sending successfule ");
Messagesent = true;
}
// Receives data callback
Private void receivedatacallback (iasyncresult AR)
{
Ipendpoint ipep = (ipendpoint) Ar. asyncstate;
Byte [] DATA = udpclient. endreceive (AR, ref ipep );
If (data. length! = 0 ){
// Onreceivedata (New udpsimpleeventargs (ipep, data ));
// String returndata = encoding. utf8.getstring (data );
// Debug. Log ("Recv data:" + returndata );
Messagereceiver. getinstance (). parsereseivemsg (data );
}
// Continue to receive the datagram from the remote host
Asyncreceive ();
}
}