mirror of
https://gitee.com/jisol/jisol-game/
synced 2025-06-26 03:14:47 +00:00
107 lines
2.9 KiB
C#
107 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Cysharp.Threading.Tasks;
|
|
using JNGame.Util;
|
|
using Plugins.JNGame.Network.Util;
|
|
using UnityEngine;
|
|
using NotImplementedException = System.NotImplementedException;
|
|
|
|
namespace Plugins.JNGame.Network
|
|
{
|
|
public abstract class JNTCPClient1 : JNClientBase
|
|
{
|
|
|
|
/// <summary>
|
|
/// 客户端
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private Socket client;
|
|
|
|
/// <summary>
|
|
/// 客户端线程
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private Thread thread;
|
|
|
|
/// <summary>
|
|
/// 是否连接
|
|
/// </summary>
|
|
public bool isConnect { get; private set; }
|
|
|
|
private Queue<byte[]> cache = new ();
|
|
|
|
public override async Task OnInit()
|
|
{
|
|
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
client.Connect(await GetEndPoint());
|
|
thread = new Thread(CreatConnectSocket);
|
|
thread.Start();
|
|
}
|
|
|
|
public override void OnClose()
|
|
{
|
|
Debug.Log($"[JNTCPClient] 关闭客户端");
|
|
base.OnClose();
|
|
client?.Close();
|
|
thread?.Abort();
|
|
}
|
|
|
|
protected virtual async UniTask<IPEndPoint> GetEndPoint()
|
|
{
|
|
await UniTask.NextFrame();
|
|
return new IPEndPoint(IPAddress.Parse("127.0.0.1"),9001);
|
|
}
|
|
|
|
private void CreatConnectSocket()
|
|
{
|
|
Debug.Log($"[JNTCPClient] 连接服务器成功");
|
|
isConnect = true;
|
|
PushCache();
|
|
byte[] bytes = new byte[102400];
|
|
try
|
|
{
|
|
while (true)
|
|
{
|
|
var max = client.Receive(bytes);
|
|
var message = new byte[max];
|
|
Array.Copy(bytes, message, max);
|
|
var param = NDataUtil.Parse(message);
|
|
Dispatch(param);
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
// ignored
|
|
Debug.LogWarning(e.Message);
|
|
Debug.Log($"[JNTCPClient] 断开连接");
|
|
isConnect = false;
|
|
client.Close();
|
|
}
|
|
}
|
|
|
|
public override void SendBytes(byte[] data)
|
|
{
|
|
if (data is null || data.Length <= 0) return;
|
|
cache.Enqueue(data);
|
|
if (isConnect)
|
|
{
|
|
PushCache();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 发送缓存
|
|
/// </summary>
|
|
public void PushCache()
|
|
{
|
|
while (isConnect && cache.TryDequeue(out var bytes))
|
|
{
|
|
NetTool.SendAsync(client,bytes);
|
|
}
|
|
}
|
|
}
|
|
} |