feat 客户端
This commit is contained in:
70
Client/Point/Assets/Scripts/Manager/SocketManager.cs
Normal file
70
Client/Point/Assets/Scripts/Manager/SocketManager.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using Google.Protobuf;
|
||||
using NativeWebSocket;
|
||||
using UnityEngine;
|
||||
|
||||
public class SocketManager : MonoBehaviour
|
||||
{
|
||||
private WebSocket _ws;
|
||||
|
||||
public static SocketManager Instance { get; private set; }
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance != null)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
public async void Connect()
|
||||
{
|
||||
_ws = new WebSocket($"wss://www.hlsq.asia/ws/?token={Random.Range(1, 1000)}");
|
||||
|
||||
_ws.OnOpen += () =>
|
||||
{
|
||||
Debug.Log("Connection open!");
|
||||
SendMessage(MessageID.EnterInstance, new C2S_EnterInstance
|
||||
{
|
||||
InstanceID = 1
|
||||
});
|
||||
};
|
||||
|
||||
_ws.OnError += (e) => { Debug.Log("Error! " + e); };
|
||||
|
||||
_ws.OnClose += (e) => { Debug.Log("Connection closed!"); };
|
||||
|
||||
_ws.OnMessage += (bytes) =>
|
||||
{
|
||||
var message = Message.Parser.ParseFrom(bytes);
|
||||
Debug.Log("OnMessage: " + message.ID);
|
||||
SocketMessageManager.Instance.TriggerEvent(message.ID, message.Payload);
|
||||
};
|
||||
|
||||
await _ws.Connect();
|
||||
}
|
||||
|
||||
public void SendMessage(MessageID id, IMessage msg)
|
||||
{
|
||||
var m = new Message
|
||||
{
|
||||
ID = id,
|
||||
Payload = ByteString.CopyFrom(msg.ToByteArray())
|
||||
};
|
||||
_ws.Send(m.ToByteArray());
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
#if !UNITY_WEBGL || UNITY_EDITOR
|
||||
_ws?.DispatchMessageQueue();
|
||||
#endif
|
||||
}
|
||||
|
||||
private async void OnApplicationQuit()
|
||||
{
|
||||
await _ws.Close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user