废话不多少上代码。。。
工程下载地址:https://download.csdn.net/download/ThreePointsHeat/12715187
下面是客户端代码:
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Net.NetworkInformation;
public class UDPClient : MonoBehaviour
{
public string recvStr;
private string UDPClientIP;
string str; //上线连接传自己的IP
Socket socket;
EndPoint serverEnd;
IPEndPoint ipEnd;
byte[] recvData = new byte[2048];
byte[] sendData = new byte[2048];
int recvLen = 0;
Thread connectThread;
public GameObject[] Obj;
void Awake()
{
str = GetIP();
}
void Start()
{
UDPClientIP = "192.168.20.141";//服务端的IP.自己更改
UDPClientIP = UDPClientIP.Trim();
InitSocket();
}
void InitSocket()
{
ipEnd = new IPEndPoint(IPAddress.Parse(UDPClientIP), 7401);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
serverEnd = (EndPoint)sender;
print("等待连接");
SocketSend(str);
print("连接");
//开启一个线程连接
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
void SocketSend(string sendStr)
{
//清空
sendData = new byte[2048];
//数据转换
sendData = Encoding.UTF8.GetBytes(sendStr);
//发送给指定服务端
socket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEnd);
}
//接收服务器信息
void SocketReceive()
{
while (true)
{
recvData = new byte[2048];
try
{
recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
}
catch (Exception e)
{
}
print("信息来自: " + serverEnd.ToString());
if (recvLen > 0)
{
recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
}
print(recvStr);
}
}
//连接关闭
void SocketQuit()
{
//关闭线程
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (socket != null)
socket.Close();
}
void OnApplicationQuit()
{
SocketQuit();
}
void Update()
{
OnOpenObj(recvStr);
ObjMove();
}
// 获取系统的IP地址
private string GetIP()
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adater in adapters)
{
if (adater.Supports(NetworkInterfaceComponent.IPv4))
{
UnicastIPAddressInformationCollection UniCast = adater.GetIPProperties().UnicastAddresses;
if (UniCast.Count > 0)
{
foreach (UnicastIPAddressInformation uni in UniCast)
{
if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
{
return uni.Address.ToString();
}
}
}
}
}
return null;
}
//
private void OnOpenObj(string recvStr)
{
switch (recvStr)
{
case "Cube":
Obj[0].SetActive(true);
break;
case "Sphere":
Obj[0].SetActive(true);
break;
default:
break;
}
}
private void ObjMove()
{
if(Input.GetKey(KeyCode.W))
{
Obj[0].transform.Translate(Vector3.forward * Time.deltaTime * 0.8f);
SocketSend("Z" + Obj[0].transform.localPosition.z.ToString());
}
if(Input.GetKey(KeyCode.S))
{
Obj[0].transform.Translate(Vector3.back * Time.deltaTime * 0.8f);
SocketSend("Z" + Obj[0].transform.localPosition.z.ToString());
}
if (Input.GetKey(KeyCode.A))
{
Obj[0].transform.Translate(Vector3.left * Time.deltaTime * 0.8f);
SocketSend("X" + Obj[0].transform.localPosition.x.ToString());
}
if (Input.GetKey(KeyCode.D))
{
Obj[0].transform.Translate(Vector3.right * Time.deltaTime * 0.8f);
SocketSend("X" + Obj[0].transform.localPosition.x.ToString());
}
}
}
下面是服务器代码:
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.UI;
using System;
public class UDPServer : MonoBehaviour
{
public Text txt;
public string ipAddress = "192.168.20.141";
public int ConnectPort = 7401;
public string recvStr;
Socket socket;
EndPoint clientEnd;
IPEndPoint ipEnd;
string sendStr = "我是服务器";
byte[] recvData = new byte[2048];
byte[] sendData = new byte[2048];
int recvLen;
Thread connectThread;
public GameObject[] Obj;
//初始化
void InitSocket()
{
ipEnd = new IPEndPoint(IPAddress.Parse(ipAddress), ConnectPort);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(ipEnd);
//定义客户端
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
clientEnd = (EndPoint)sender;
print("等待连接数据");
//开启一个线程连接
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
void SocketSend(string sendStr)
{
sendData = new byte[2048];
sendData = Encoding.UTF8.GetBytes(sendStr);
socket.SendTo(sendData, sendData.Length, SocketFlags.None, clientEnd);
}
//服务器接收
void SocketReceive()
{
while (true)
{
recvData = new byte[2048];
recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
Debug.Log("收到得信息 " + recvStr);
txt.text = recvStr;
}
}
//连接关闭
void SocketQuit()
{
//关闭线程
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (socket != null)
socket.Close();
Debug.LogWarning("断开连接");
}
// Use this for initialization
void Start()
{
InitSocket(); //在这里初始化server
}
void OnApplicationQuit()
{
SocketQuit();
}
private void Update()
{
if(Input.GetKey(KeyCode.Space))
{
SocketSend("Cube");
Obj[0].SetActive(true);
}
if(recvStr.Substring(0, 1) == "Z")
{
float Zpos = Convert.ToSingle(recvStr.Substring(1));
Obj[0].transform.localPosition = new Vector3(Obj[0].transform.localPosition.x, Obj[0].transform.localPosition.y,Zpos);
}
if (recvStr.Substring(0, 1) == "X")
{
float Xpos = Convert.ToSingle(recvStr.Substring(1));
Obj[0].transform.localPosition = new Vector3(Xpos, Obj[0].transform.localPosition.y, Obj[0].transform.localPosition.z);
}
}
}
因为是做仿真项目需要用到局域网下协同,最开始使用的是Networking,简单是简单,但是不稳定还有局限性;最后在网上借鉴了很多博主的写法,自己实现了UDP通信。
下面是Demo截图: