所以我已经建立了一个C#TCP服务器,但是每当我连接多个客户端进行测试时,整个设备就开始出现滞后,内存变为500 MB,早于1GB。我知道这与代码结构有关,所以我不确定是什么造成了这种情况。 Image. Console.
基本上,这是我的服务器类。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Roleplay_Flash_Server.assets.communication
{
class server
{
private static TcpListener serverHandle;
private const string prefix = "[communication->server.cs] ";
private static bool responded = false;
public static void init(int port)
{
serverHandle = new TcpListener(IPAddress.Any, port);
serverHandle.Start();
Console.WriteLine("Waiting on a client...");
while (responded == false)
{
serverHandle.BeginAcceptTcpClient(HandleAsyncConnection, serverHandle);
//responded = false;
}
}
private static void HandleAsyncConnection(IAsyncResult response)
{
responded = true;
serverHandle.BeginAcceptTcpClient(HandleAsyncConnection, serverHandle);
TcpClient client = serverHandle.EndAcceptTcpClient(response);
communication.client.incoming.connection(client);
communication.client.events.pingIntervalEvent.init(client);
communication.client.events.handshakeEvent.init(client);
while(true)
{
string test = readRequest(client);
}
destruct(client);
}
public static string readRequest(TcpClient socket)
{
byte[] data = new byte[1024];
int response = socket.Client.Receive(data);
if (response == 0) return "";
string clientIP = ((IPEndPoint)socket.Client.RemoteEndPoint).Address.ToString();
string clientPort = ((IPEndPoint)socket.Client.RemoteEndPoint).Port.ToString();
Console.Write(prefix + "Received data from {#" + "?" + "}, {" + clientIP + ":" + clientPort + "}: " + Encoding.ASCII.GetString(data, 0, response));
return Encoding.ASCII.GetString(data, 0, response);
}
private static void destruct(TcpClient socket)
{
string clientIP = ((IPEndPoint)socket.Client.RemoteEndPoint).Address.ToString();
string clientPort = ((IPEndPoint)socket.Client.RemoteEndPoint).Port.ToString();
Console.Write(prefix + "Lost connection with {#" + "?" + "}, {" + clientIP + ":" + clientPort + "}.");
socket.Close();
}
}
}
编辑:可能导致此内存溢出的所有类:
答案 0 :(得分:0)
所以我通过简单地从异步回调中移除BeginAcceptTcpClient
来解决这个问题,这导致函数在无限循环中调用,但也在循环调用的另一个回调中调用,内存溢出。