using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System;
public class UDPServer : MonoBehaviour
{ [HideInInspector]
public static UDPServer instance;
Socket socket; //目标socket
EndPoint clientEnd; //客户端
IPEndPoint ipEnd; //侦听端口
public string recvStr; //接收的字符串
string sendStr; //发送的字符串
byte[] recvData = new byte[1024]; //接收的数据,必须为字节
byte[] sendData = new byte[1024]; //发送的数据,必须为字节
int recvLen; //接收的数据长度
Thread connectThread; //连接线程
[HideInInspector]
public bool isStartSend=false;
/// <summary>
/// 初始化
/// </summary>
void InitSocket()
{
//定义侦听端口,侦听任何IP
ipEnd = new IPEndPoint(IPAddress.Any, 8888);
//定义套接字类型,在主线程中定义
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
//服务端需要绑定ip
socket.Bind(ipEnd);
//定义客户端
IPEndPoint sender = new IPEndPoint(IPAddress.Broadcast, 0);
clientEnd = (EndPoint)sender;
print("local:等待连接数据");
//开启一个线程连接,必须的,否则主线程卡死
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
/// <summary>
/// 服务器向客户端发送消息
/// </summary>
/// <param name="sendStr"></param>
public void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.UTF8.GetBytes(sendStr);
//发送给指定客户端
socket.SendTo(sendData, sendData.Length, SocketFlags.None, clientEnd);
}
bool isServerActive = false;
/// <summary>
/// 服务器接收来自客户端的消息
/// </summary>
void SocketReceive()
{
//进入接收循环
while (isServerActive)
{
//对data清零
recvData = new byte[1024];
try
{
//获取服务端端数据
recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
if (isServerActive == false)
{
break;
}
}
catch (Exception e)
{
print(e.Message);
}
//打印客户端信息
// print("local:"+clientEnd.ToString()+"连接");
recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
//输出接收到的数据
Debug.Log("Clent:" + recvStr);
//此处可以写服务端接收到客户端消息后作出的反应
//将接收到的数据经过处理再发送出去
// sendStr = "服务器: 我收到--" + recvStr+"--消息";
// SocketSend(sendStr);
//客户端心跳回馈
HeartCheck(recvStr);
}
}
float timerInterval = 0;
bool isStartCheck = false;
void HeartCheck(string str) {
string heartStr = str;
if (heartStr == "alive")
{
isStartCheck = true;
timerInterval = 0f;
SocketSend("keeping");
heartStr = "";
//通知cube开始发送消息
if (!isStartSend)
{
isStartSend = true;
}
}
}
void Update() {
timerInterval += Time.deltaTime;
if (isStartCheck)
{
if (timerInterval>3f)
{
print("网络连接异常");
isStartCheck = false;
}
}
}
//连接关闭
void SocketQuit()
{
//关闭线程
// if (connectThread != null)
// {
//connectThread.Interrupt();
// connectThread.Abort();
// }
//最后关闭socket
if (socket != null)
socket.Close();
Debug.LogWarning("local:断开连接");
}
private void Awake()
{
instance = this;
}
void Start()
{
isServerActive = true;
InitSocket(); //在这里初始化server
}
void OnApplicationQuit()
{
isServerActive = false;
SocketQuit();
Thread.Sleep(25);
}
public bool Vector3Type(string str) {
if (str.Contains("(") && str.Contains(")") && str.Contains(","))
{
return true;
}
else {
return false;
}
}
/// <summary>
/// 将字符串转换为vector3类型
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Vector3 Vector3Parse(string name) {
//去掉()
name = name.Replace("(", "").Replace(")", "");
//切割字符串
string[] s = name.Split(',');
//转换为float类型 返回vector3类型
return new Vector3(float.Parse(s[0]), float.Parse(s[1]), float.Parse(s[2]));
}
}
网友评论