Commit eea918a9 authored by hex's avatar hex

Optimized TcpHelper.cs

parent d2b594a5
Pipeline #38589 failed
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO; using System.IO;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
...@@ -12,10 +13,13 @@ public static class TcpHelper ...@@ -12,10 +13,13 @@ public static class TcpHelper
{ {
public static TcpClient tcpClient = null; 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; public static bool onDisConnected = false;
static bool roomListChecking = false;
private static ConcurrentQueue<byte[]> datas = new ConcurrentQueue<byte[]>();
public static void join( public static void join(
string ipString, string ipString,
...@@ -89,33 +93,26 @@ public static class TcpHelper ...@@ -89,33 +93,26 @@ public static class TcpHelper
public static void addDateJumoLine(byte[] data) public static void addDateJumoLine(byte[] data)
{ {
Monitor.Enter(datas); // 不再需要手动加锁 Monitor.Enter/Exit
// ConcurrentQueue.Enqueue 本身就是线程安全的。
try try
{ {
datas.Add(data); datas.Enqueue(data);
} }
catch (System.Exception e) catch (System.Exception e)
{ {
// 保留异常处理逻辑
UnityEngine.Debug.Log(e); UnityEngine.Debug.Log(e);
} }
Monitor.Exit(datas);
} }
public static bool onDisConnected = false;
static List<byte[]> datas = new List<byte[]>();
public static void preFrameFunction() public static void preFrameFunction()
{ {
if (datas.Count > 0)
{ while (datas.TryDequeue(out byte[] data))
if (Monitor.TryEnter(datas))
{
for (int i = 0; i < datas.Count; i++)
{ {
try try
{ {
MemoryStream memoryStream = new MemoryStream(datas[i]); MemoryStream memoryStream = new MemoryStream(data);
BinaryReader r = new BinaryReader(memoryStream); BinaryReader r = new BinaryReader(memoryStream);
var ms = (StocMessage)(r.ReadByte()); var ms = (StocMessage)(r.ReadByte());
switch (ms) switch (ms)
...@@ -202,10 +199,7 @@ public static class TcpHelper ...@@ -202,10 +199,7 @@ public static class TcpHelper
// Program.DEBUGLOG(e); // Program.DEBUGLOG(e);
} }
} }
datas.Clear();
Monitor.Exit(datas);
}
}
if (onDisConnected == true) if (onDisConnected == true)
{ {
onDisConnected = false; 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