1.接收来自服务器的消息
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;public class UDPManager:MonoBehaviour
{public string recvStr; //服务器返回值public string UDPClientAddRess = "192.168.2.39"; //目标服务器地址public int UDPClientPort = 8080; //目标服务器端口号Socket socket;EndPoint serverEnd;IPEndPoint ipEnd;byte[] recvData = new byte[1024];byte[] sendData = new byte[1024];int recvLen = 0;Thread connectThread;/// <summary>/// 想服务器发送数据/// </summary>/// <param name="message"></param>public void InitSocket(string message){Debug.Log(message);UDPClientAddRess = UDPClientAddRess.Trim();ipEnd = new IPEndPoint(IPAddress.Parse(UDPClientAddRess), UDPClientPort);socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);serverEnd = sender;Debug.Log("等待链接");SocketSend(message);Debug.Log("连接成功");connectThread = new Thread(new ThreadStart(SocketReceve));connectThread.Start();}/// <summary>/// 想服务端发送需要发送的内容/// </summary>/// <param name="sendMessage"></param>public void SocketSend(string sendMessage){//首先清空所有sendData = new byte[1024];//转换数据sendData = Encoding.UTF8.GetBytes(sendMessage);//将数据发送到服务端socket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEnd);}/// <summary>/// 接收来自服务端的消息/// </summary>void SocketReceve(){while (true){recvData = new byte[1024];try{recvLen = socket.ReceiveFrom(recvData, ref serverEnd);}catch (System.Exception e){Debug.LogError("出现异常,异常信息:" + e);}Debug.Log("收到信息,信息来自:" + serverEnd.ToString());if (recvLen > 0){recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);Debug.Log(recvStr);}else{Debug.LogError("出现错误,请检查网络链接是否正常");}}}/// <summary>/// 关闭与服务器的连接/// </summary>public void SocketQuit(){//如果线程还在就需要关闭线程Debug.Log("销毁UDP");if (connectThread != null){connectThread.Interrupt();connectThread.Abort();}//最后关闭socketif (socket != null){socket.Close();}}
}
2.给服务器发送消息