【发布时间】:2018-08-02 10:25:16
【问题描述】:
所以我创建了一个 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();
}
}
}
编辑:所有可能导致内存溢出的类:
【问题讨论】:
-
我怀疑分配内存的代码是这个,一定是在外面。
-
您在调试器中运行时正在测量内存:这会增加大量开销。如果您在调试器之外运行并检查内存(即使任务管理器也会进行快速检查,但性能计数器会更好)您会看到什么?
-
这是唯一一个使用不定式循环的类,我可以看到构造这个类时内存在物理上增加,每 ½ 秒增加 4 MB 或更多。 @古斯曼
-
@Richard 即使是这样,我也不认为调试器会在其工具上增加额外的千兆字节?这是我记忆的八分之一。
-
你正在做 webrequests 并且没有处理任何东西,这可能会导致内存泄漏。处理所有实现
IDisposable的东西。
标签: c# .net memory tcplistener tcpserver