我现在正在开发一种服务,它可以侦听 TCP 协议中的消息,并将它们发送到不同的目的地。
所以我定义了一个套接字,它始终保持打开状态并获取消息。协议的大小是静态的,消息一次到达几个。
只要接收到值并削减消息的匹配大小,循环就会运行。
该服务运行良好-根据需要接收所有消息,但内存不断增加。实施:
public void WaitingForClient()
{
while (true)
{
// Accept will block until someone connects
m_Socket = m_TcpLsn.AcceptSocket();
ThreadPool.QueueUserWorkItem(new WaitCallback(ReadSocket));
}
}
//Read the data from the socket
public void ReadSocket(object obj)
{
Socket s = m_Socket;
if (s.Connected)
{
Byte[] receive = new Byte[MESSAGE_LENGTH];
try
{
// Receive will block until data coming
// ret is 0 or Exception happen when Socket connection is broken
int ret = s.Receive(receive, receive.Length, 0);
while (ret > 0)
{
OnMessageRecieved(new RecievedMessage(receive));
**receive = new Byte[MESSAGE_LENGTH];**
ret = s.Receive(receive, receive.Length, SocketFlags.None);
}
}
我在网络内存分析器中看到缓冲区(循环中定义的字节数组)永远不会被释放,因此存在内存泄漏问题。在每次发送消息时,都会创建另一个字节数组实例,并且没有任何内容被释放。
我试图编写一个循环,以这种方式将数组初始化为空值:
try
{
// Receive will block until data coming
// ret is 0 or Exception happen when Socket connection is broken
int ret = s.Receive(receive, receive.Length, 0);
while (ret > 0)
{
OnMessageRecieved(new RecievedMessage(receive));
for (int i = 0; i < MESSAGE_LENGTH; i++)
{
receive[i] = 00;
}
ret = s.Receive(receive, receive.Length, SocketFlags.None);
}
但是随后部分消息以空值而不是正确的值发送(连接在一起的消息)。
我该如何解决?