Commit eea918a9 authored by hex's avatar hex

Optimized TcpHelper.cs

parent d2b594a5
Pipeline #38589 failed
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Net.Sockets;
using System.Text;
......@@ -12,10 +13,13 @@ public static class TcpHelper
{
public static TcpClient tcpClient = null;
static NetworkStream networkStream = null;
private static NetworkStream networkStream = null;
private static bool canjoin = true;
private static bool roomListChecking = false;
static bool canjoin = true;
static bool roomListChecking = false;
public static bool onDisConnected = false;
private static ConcurrentQueue<byte[]> datas = new ConcurrentQueue<byte[]>();
public static void join(
string ipString,
......@@ -89,33 +93,26 @@ public static class TcpHelper
public static void addDateJumoLine(byte[] data)
{
Monitor.Enter(datas);
// 不再需要手动加锁 Monitor.Enter/Exit
// ConcurrentQueue.Enqueue 本身就是线程安全的。
try
{
datas.Add(data);
datas.Enqueue(data);
}
catch (System.Exception e)
{
// 保留异常处理逻辑
UnityEngine.Debug.Log(e);
}
Monitor.Exit(datas);
}
public static bool onDisConnected = false;
static List<byte[]> datas = new List<byte[]>();
public static void preFrameFunction()
{
if (datas.Count > 0)
{
if (Monitor.TryEnter(datas))
{
for (int i = 0; i < datas.Count; i++)
while (datas.TryDequeue(out byte[] data))
{
try
{
MemoryStream memoryStream = new MemoryStream(datas[i]);
MemoryStream memoryStream = new MemoryStream(data);
BinaryReader r = new BinaryReader(memoryStream);
var ms = (StocMessage)(r.ReadByte());
switch (ms)
......@@ -202,10 +199,7 @@ public static class TcpHelper
// Program.DEBUGLOG(e);
}
}
datas.Clear();
Monitor.Exit(datas);
}
}
if (onDisConnected == true)
{
onDisConnected = false;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment