Created
May 1, 2022 04:45
-
-
Save Tunied/7c93f07e1598ebf50780504eee58e613 to your computer and use it in GitHub Desktop.
监听某个端口的UDP消息
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; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading; | |
using UnityEngine; | |
namespace Code.Dev.Network | |
{ | |
public class Test_UDP_Receive : MonoBehaviour | |
{ | |
// receiving Thread | |
Thread receiveThread; | |
// udpclient object | |
UdpClient client; | |
// public | |
// public string IP = "127.0.0.1"; default local | |
public int port; // define > init | |
// start from unity3d | |
public void Start() { init(); } | |
private void OnDestroy() | |
{ | |
receiveThread.Abort(); | |
Debug.Log("Stop UDP Server"); | |
} | |
// init | |
private void init() | |
{ | |
print("UDP Receive Init"); | |
receiveThread = new Thread(ReceiveData) { }; | |
receiveThread.Start(); | |
} | |
// receive thread | |
private void ReceiveData() | |
{ | |
print("监听端口收到数据...."); | |
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); | |
print(">> " + text); | |
} | |
catch (Exception err) | |
{ | |
print(err.ToString()); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment