-
-
Save unitycoder/7ad714e72f5fed1c50c6d7a188082388 to your computer and use it in GitHub Desktop.
UDP Listener Receiver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Net.Sockets; | |
using UnityEngine; | |
public class UDPListener : MonoBehaviour | |
{ | |
UdpClient clientData; | |
int portData = 50505; | |
public int receiveBufferSize = 120000; | |
public bool showDebug = false; | |
IPEndPoint ipEndPointData; | |
private object obj = null; | |
private System.AsyncCallback AC; | |
byte[] receivedBytes; | |
void Start() | |
{ | |
InitializeUDPListener(); | |
} | |
public void InitializeUDPListener() | |
{ | |
ipEndPointData = new IPEndPoint(IPAddress.Any, portData); | |
clientData = new UdpClient(); | |
clientData.Client.ReceiveBufferSize = receiveBufferSize; | |
clientData.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true); | |
clientData.ExclusiveAddressUse = false; | |
clientData.EnableBroadcast = true; | |
clientData.Client.Bind(ipEndPointData); | |
clientData.DontFragment = true; | |
if (showDebug) Debug.Log("BufSize: " + clientData.Client.ReceiveBufferSize); | |
AC = new System.AsyncCallback(ReceivedUDPPacket); | |
clientData.BeginReceive(AC, obj); | |
Debug.Log("UDP - Start Receiving.."); | |
} | |
void ReceivedUDPPacket(System.IAsyncResult result) | |
{ | |
//stopwatch.Start(); | |
receivedBytes = clientData.EndReceive(result, ref ipEndPointData); | |
ParsePacket(); | |
clientData.BeginReceive(AC, obj); | |
//stopwatch.Stop(); | |
//Debug.Log(stopwatch.ElapsedTicks); | |
//stopwatch.Reset(); | |
} // ReceiveCallBack | |
void ParsePacket() | |
{ | |
// work with receivedBytes | |
Debug.Log("receivedBytes len = " + receivedBytes.Length); | |
} | |
void OnDestroy() | |
{ | |
if (clientData != null) | |
{ | |
clientData.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/codemaker2015/unity-udp-demo