Unity实现UDP客户端与服务器通信功能
前言
在Unity开发中,我们开发的程序经常需要和服务器或者其他的客户端进行通信,以便进行数据的传输。通信分好几种,比如TCP/IP,UDP,Socket等等。在之前的项目中,我做过一些使用UDP进行通信的项目。在这篇博客中我记录一下使用UDP实现一种最简单的客户端与服务器进行通信功能的流程。
实现步骤
1.在Unity项目中新建UDP通信脚本,代码如下所示:
using UnityEngine;
using System.Collections;
//引入库
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using UnityEngine.UI;
public class Udp : MonoBehaviour
{
//以下默认都是私有的成员
//Socket socketSend; //发送socket
UdpClient socketSend;
IPEndPoint ipSend; //客户端端口
Socket socketReceive; //接收socket
IPEndPoint ipReceive; //服务端端口
List<EndPoint> clientEnds; //客户端
string recvStr; //接收的字符串
string sendStr; //发送的字符串
byte[] recvData = new byte[1024]; //接收的数据,必须为字节
byte[] sendData = new byte[1024]