1.接收端:
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
public class UDPClient2Msg : MonoBehaviour {
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
IPEndPoint remotePoint;
Thread thread= null;
private bool ChangeScene;
// Use this for initialization
void Start () {
remotePoint = new IPEndPoint(IPAddress.Any, 0);
thread = new Thread(ReceiveMsg);
thread.Start();
}
string stateStr = "STATE-END";
void ReceiveMsg()
{
while (true)
{
// u3d接收端口
client = new UdpClient(9000);
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.UTF8.GetString(receiveData);
Debug.Log(receiveString + "----------->");
if (receiveString.Trim().CompareTo("STATE-END") != 0)
{
ChangeScene = true;
}
client.Close();//关闭连接
}
}
void Update()
{
if (ChangeScene)
{
ChangeScene = false;
receiveString = null;
SceneManager.LoadScene("Scene0-ZLoadingScene");
Debug.Log("切换场景");
}
}
void SocketQuit()
{
thread.Abort();
thread.Interrupt();
client.Close();
}
void OnDestroy()
{
SocketQuit();
}
void OnApplicationQuit()
{
SocketQuit();
}
}
2.发送端:
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
/// <summary>
/// 发送脚本
/// </summary>
public class UDPClient1Msg : MonoBehaviour {
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
UdpClient client = null;
public static UDPClient1Msg Instance;
private void Awake()
{
Instance = this;
}
public void SendMsg(string sendStr)
{
IPAddress remoteIP = IPAddress.Parse("127.0.0.1"); //假设发送给这个IP
int remotePort = 9000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点
if (sendStr != null)
{
sendData = Encoding.Default.GetBytes(sendStr);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
client.Close();//关闭连接
sendString = null;
}
}
}