我应该在每次交易后关闭套接字 (TCPIP) 吗? [英] Should I close a socket (TCPIP) after every transaction?

查看:24
本文介绍了我应该在每次交易后关闭套接字 (TCPIP) 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 TCPIP 服务器,它实现了 FileSystemWatcher 并用从 FSW 获取的新文件中解析的数据填充队列.

I have written a TCPIP server that implements a FileSystemWatcher and fills a queue with data parsed from new files acquired by the FSW.

单个客户端将连接到此服务器并从队列中请求数据(任何时候都不需要其他客户端连接).如果没有数据存在,客户端将等待(1 秒)并重试.

A single client will connect to this server and ask for data from the queue (no other client will need to connect at any time). If no data exists, the client will wait (1 second) and try again.

客户端和服务器都是异步编写的——我的问题是:客户端应该为每个事务创建一个新的套接字(在 while 循环内),还是只是让套接字保持打开状态(在 while 循环外)?

Both client and server are written asynchronously - my question is: should the client create a new socket for each transaction (inside the while loop), or just leave the socket open (outside the while loop)?

client.Connect()

while(bCollectData)
{
    ... communicate ...

    Thread.Sleep(1000);
}

client.Shutdown(SocketShutdown.Both);
client.Close();

推荐答案

我建议你让套接字保持打开状态,甚至更好地在服务器上阻止它,这样你就不必执行 Thread.Sleep.当服务器有一些数据时,他会将消息发送给客户端.

I would suggest you to leave socket open and even better to block it on the server, so that you didn't have to do Thread.Sleep. When the server will have some data he will send the message to the client.

代码看起来像这样

while(bCollectData)
{
   _socket.recv(...); //this line will wait for response from server
   //... process message and start another wait in the next iteration.
}

使用这种方法,您将立即获得所有消息,并避免在客户端和服务器之间发送不需要的消息(返回该服务器的消息没有数据).

using this approach you will get all messages immediately and avoid unneeded messages sent between client and server(the messages which return that server has no data).

这篇关于我应该在每次交易后关闭套接字 (TCPIP) 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆