赞
踩
记录一下Unity WebSocket的简单用法
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityWebSocket;
public class WebSocketLogic :MonoBehaviour
{
private WebSocketLogic() { }
private WebSocketLogic _instance;
private bool connected = false;
private bool inited = false;
private Dictionary<SocketCode, List<Action<string>>> msgResponseDic = new Dictionary<SocketCode, List<Action<string>>>();
private Dictionary<SocketCode, List<Action<string>>> msgListenerDic = new Dictionary<SocketCode, List<Action<string>>>();
public WebSocketLogic Instance
{
get
{
if (_instance == null)
{
_instance = new WebSocketLogic();
}
return _instance;
}
private set { }
}
WebSocket webSocket;
string ip;
public void Init(string _ip)
{
inited = true;
ip = _ip;
}
public void Connect()
{
RemoveHandle();
webSocket = new WebSocket(ip);
webSocket.OnClose += WebSocketClose;
webSocket.OnOpen += WebSocketOpen;
webSocket.OnError += WebSocketError;
webSocket.OnMessage += WebSocketReceive;
webSocket.ConnectAsync();
}
public void AddListener(SocketCode socketCode,Action<string> callback)
{
if (msgListenerDic.ContainsKey(socketCode))
{
List<Action<string>> actions = msgListenerDic[socketCode];
for (int i = 0; i < actions.Count; i++)
{
if (actions[i] == callback)
{
Debug.LogError("重复注册监听,消息号:" + socketCode);
return;
}
}
msgListenerDic[socketCode].Add(callback);
}
else
{
List<Action<string>> actions = new List<Action<string>>();
actions.Add(callback);
msgListenerDic.Add(socketCode, actions);
}
}
public void RemoveListener(SocketCode socketCode,Action<string> callback)
{
if (msgListenerDic.ContainsKey(socketCode))
{
List<Action<string>> actions = msgListenerDic[socketCode];
for (int i = 0; i < actions.Count; i++)
{
if (actions[i] == callback)
{
actions.RemoveAt(i);
return;
}
}
Debug.LogError("移除监听出错,未包注册监听消息函数,消息号:" + socketCode);
}
else
{
Debug.LogError("移除监听出错,未包注册监听,消息号:" + socketCode);
}
}
void RemoveHandle()
{
msgResponseDic.Clear();
webSocket = null;
webSocket.OnClose -= WebSocketClose;
webSocket.OnOpen -= WebSocketOpen;
webSocket.OnError -= WebSocketError;
webSocket.OnMessage -= WebSocketReceive;
}
public void Send(SocketCode socketCode, string msg,Action<string> callback)
{
if (callback != null)
{
if (msgResponseDic.ContainsKey(socketCode))
{
msgResponseDic[socketCode].Add(callback);
}
else
{
List<Action<string>> actions = new List<Action<string>>();
actions.Add(callback);
msgResponseDic.Add(socketCode, actions);
}
}
webSocket.SendAsync(string.Format("{0}/{1}", socketCode, msg));
}
private void WebSocketReceive(object sender, MessageEventArgs e)
{
//优化逻辑
//heartTime = 0;
receiveMsgTime = Time.realtimeSinceStartup;
if (e.IsText)
{
string[] temp = e.Data.Split('.');
//发送接口需要返回的消息
SocketCode socketCode = (SocketCode)int.Parse(temp[0]);
if (msgResponseDic.ContainsKey(socketCode))
{
List<Action<string>> actions = msgResponseDic[socketCode];
for (int i = 0; i < actions.Count; i++)
{
actions[i](temp[1]);
}
msgResponseDic.Remove(socketCode);
}
if (msgListenerDic.ContainsKey(socketCode))
{
List<Action<string>> actions = msgListenerDic[socketCode];
for (int i = 0; i < actions.Count; i++)
{
actions[i](temp[1]);
}
}
Debug.LogError(string.Format("接收到消息: {0}", e.Data));
}
else if (e.IsBinary)
{
Debug.LogError(string.Format("接受到消息 Bytes ({1}): {0}", e.Data, e.RawData.Length));
}
}
private void WebSocketError(object sender, ErrorEventArgs e)
{
connected = false;
throw new NotImplementedException();
}
private void WebSocketOpen(object sender, OpenEventArgs e)
{
reconnectCount = 0;
receiveMsgTime = Time.realtimeSinceStartup;
connected = true;
Debug.LogError(string.Format("连接成功,IP:{0}",ip));
}
private void WebSocketClose(object sender, CloseEventArgs e)
{
connected = false;
Debug.LogError(string.Format("连接关闭: StatusCode: {0}, Reason: {1}", e.StatusCode, e.Reason));
}
float heartTime = 0;
float receiveMsgTime = 0;
float reconnectCount = 0;
private void Update()
{
if (!inited)
{
return;
}
heartTime = heartTime + Time.deltaTime;
if (heartTime >= 5.0f && connected == true)
{
heartTime = 0.0f;
Send(SocketCode.Heart, "heartbeat",null);
}
if (receiveMsgTime != 0 &&Time.realtimeSinceStartup - receiveMsgTime > 6.0f)
{
if (reconnectCount > 5)
{
Debug.LogError("重新连接失败!");
return;
}
receiveMsgTime = Time.realtimeSinceStartup;
connected = false;
webSocket.CloseAsync();
Connect();
reconnectCount = reconnectCount + 1;
Debug.LogError(string.Format("连接断开,尝试第{0}次重新连接!", reconnectCount));
}
}
public void Clear()
{
connected = false;
inited = false;
msgResponseDic.Clear();
msgListenerDic.Clear();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。