PC-20230316NUNE\Administrator a1f2730025 Tile服务器雏形..
2024-08-19 11:51:17 +08:00

88 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using BestHTTP.WebSocket;
using Cysharp.Threading.Tasks;
using DotRecast.Core.Collections;
using Google.Protobuf;
using Plugins.JNGame.Network.Entity;
using Plugins.JNGame.Network.Util;
using Plugins.JNGame.Util;
using UnityEngine;
namespace Plugins.JNGame.Network
{
public abstract class JNSocket : JNClientBase
{
private WebSocket _socket;
private UniTaskCompletionSource _onOpen;
public override async Task OnInit()
{
await StartConnect();
}
public async Task StartConnect()
{
var url = $"{await this.GetUrl()}";
this._socket = new WebSocket(new Uri(url));
this._socket.OnOpen += OnOpen;
this._socket.OnMessage += OnMessageReceived;
this._socket.OnError += OnError;
this._socket.OnClosed += OnClosed;
this._socket.OnBinary += Onbinary;
Debug.Log($"[JNSocket]初始化WebSocket成功URL{url}");
this._socket.Open();
//等待连接成功
await (this._onOpen = new UniTaskCompletionSource()).Task;
}
private void OnOpen(WebSocket websocket)
{
Debug.Log($"[JNSocket] OnOpen");
this._onOpen.TrySetResult();
}
private void OnMessageReceived(WebSocket websocket, string message)
{
Debug.Log($"[JNSocket] OnMessageReceived");
}
private void OnError(WebSocket websocket, string reason)
{
Debug.Log($"[JNSocket] OnError");
}
private void OnClosed(WebSocket websocket, ushort code, string message)
{
Debug.Log($"[JNSocket] OnClosed");
}
private void Onbinary(WebSocket websocket, byte[] data)
{
// NSystem.Log($"[JNSocket] Onbinary");
Dispatch(NDataUtil.Parse(data));
}
protected abstract UniTask<string> GetUrl();
public override void SendBytes(byte[] data)
{
_socket.Send(data);
}
}
}