PC-20230316NUNE\Administrator 8932528f5e 提交bug 艰难先这样
2024-08-22 20:37:39 +08:00

70 lines
1.9 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 TouchSocket.Core;
using TouchSocket.Http.WebSockets;
using TouchSocket.Sockets;
using UnityEngine;
namespace Plugins.JNGame.Network
{
public abstract class JNSocket : JNClientBase
{
private WebSocketClient client;
public override async Task OnInit()
{
await StartConnect();
}
public async Task StartConnect()
{
client = new WebSocketClient();
await client.SetupAsync(new TouchSocketConfig()
.SetRemoteIPHost(await this.GetUrl())
.ConfigurePlugins(a =>
{
a.UseReconnection(-1, true, 1000); //如需永远尝试连接tryCount设置为-1即可。
})
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
}));
client.Received += OnReceived;
client.Connect();
Debug.Log($"[JNSocket]连接WebSocket成功");
}
private Task OnReceived(WebSocketClient webSocketClient, WSDataFrameEventArgs e)
{
if (e.DataFrame.Opcode == WSDataType.Binary && e.DataFrame.FIN)
{
Dispatch(NDataUtil.Parse(e.DataFrame.PayloadData));
}
return Task.CompletedTask;
}
protected abstract UniTask<string> GetUrl();
public override void SendBytes(byte[] data)
{
client.SendAsync(data);
}
}
}