我现在正在开发一种侦听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);
}
}
我在net memory profiler中看到缓冲区(一个字节数组在循环中定义),永远不会被释放,因此存在内存泄漏问题。在每次发送消息时,都会创建另一个字节数组的实例。什么都没有被释放。
我尝试编写一个循环,以这种方式初始化数组:
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);
}
但是部分消息是以空值而不是正确的值(连接在一起的消息)发送的。
我该如何解决?