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

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

问题描述

我已经写了一个实现FileSystemWatcher的,填补与由FSW收购新文件解析的数据队列中TCPIP服务器。



一个单一的客户端将连接到该服务器并请求从队列中的数据(没有其它客户端将需要随时连接)。如果没有数据存在,客户端将等待(1秒),然后重试。



客户端和服务器异步写入 - 我的问题是:应在客户端创建一个新的插座每笔交易(while循环中),或者只是把socket打开(while循环外)?

 客户端。连接()

,而(bCollectData)
{
... ...沟通

Thread.sleep代码(1000);
}

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


解决方案

我建议你离开套接字打开,甚至更好阻止它在服务器上,这样你没有做的Thread.Sleep。当服务器都会有一些数据,他将消息发送到客户端。



该代码将是这个样子

 而(bCollectData)
{
_socket.recv(...); //这条线将等待来自服务器
// ...工艺消息响应,并开始下一次迭代另一个等待。
}



使用这种方法,你会立刻得到所有的信息,避免客户端之间发送不需要的邮件和服务器(返回服务器没有数据的消息)。


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

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.

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();

解决方案

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.

The code will look something like this

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天全站免登陆