赞
踩
准备:
首先写一个UDP连接总类,这个类只管UDP的收和发代码如下:
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using UnityEngine;
-
- public class UDPManager
- {
- public string recvStr; //服务器返回值
- public string UDPClientAddRess = "127.0.0.1"; //目标服务器地址
- public int UDPClientPort = 1081; //目标服务器端口号
- 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)
- {
- 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>
- 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();
- }
- //最后关闭socket
- if(socket != null)
- {
- socket.Close();
- }
- }
- }
我们所有的连接都要通过这个类进行连接
然后我们写一个类进行数据的发送
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class SendMessage : MonoBehaviour
- {
- UDPManager udpMgr;
- // Start is called before the first frame update
- void Start()
- {
- udpMgr = new UDPManager();
- }
- public void Send()
- {
- udpMgr.InitSocket("这里输入你需要发送的内容");
- }
- /// <summary>
- /// 程序最后退出时销毁udp
- /// </summary>
- void OnDisable()
- {
- udpMgr.SocketQuit();
- }
- }
收到消息会打印出来
注意事项:
由于开启了一个新的线程,所以继承自MonoBehaviour的很多方法不能直接调用,需要自行想办法去解决,建议通过update判断值执行方法后初始化值,很多很多方法,看自己去发现,这里不再多讲,本博客会持续更新,目前为残次,很多东西都没有处理,装上勿喷 谢谢合作
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。