using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.IO;
using System;
public class oscnet : MonoBehaviour {
public Socket MySocket;
public string IpAdree= "127.0.0.1";
public int port=7878;
Thread connectThread;
void Start () {
MySocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
MySocket.Bind(new IPEndPoint(IPAddress.Parse(IpAdree), port));
connectThread = new Thread(new ThreadStart(ReciveMsg));
connectThread.Start();
}
public void ReciveMsg()
{
Debug.Log("开始线程了~");
while (true)
{
EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int count = MySocket.ReceiveFrom(data, ref endPoint);
string msg = System.Text.Encoding.UTF8.GetString(data, 0, count);
Debug.Log("接收到:"+ msg);
}
}
void Update () {
}
private void OnDestroy()
{
Debug.Log("关闭线程了");
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (MySocket != null)
MySocket.Close();
}
}
unity UDP
最新推荐文章于 2024-06-27 15:28:09 发布