插座在1秒内打开和关闭或保持打开状态 [英] Socket open and close on 1 sec or to hold open

查看:99
本文介绍了插座在1秒内打开和关闭或保持打开状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定期与plc通信(每1秒),我发送消息并收到消息。我使用 Socket 类进行此通信。我是否需要每1秒打开一次连接( socket = new Socket(ipaddress,port)),发送消息然后 socket.close()依此类推,或者一直保持套接字操作?

I need to have periodically communication with plc ( on every 1 sec ), I send message and I receive message. I use Socket class for this communication. Do I need to every 1 sec to open connection ( socket=new Socket(ipaddress, port) ), send messagethen socket.close() and so on , or to hold socket opet all time ?

推荐答案

我假设你在说话关于这里的TCP套接字......

I'll assume you're talking about TCP sockets here...

除了每秒设置TCP连接所带来的明显效率低下之外,你还可能最终在<$ c中累积套接字$ c> TIME_WAIT (希望在您的客户端上)。

Apart from the obvious inefficiencies involved in setting up a TCP connection every second you're also likely to end up accumulating sockets in TIME_WAIT (hopefully on your client).

我写的是关于 TIME_WAIT 以及我在博客上关于服务器可扩展性和稳定性的问题: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for- protocols-and-scalable-servers.html

I've written about TIME_WAIT and the problems it causes with regards to server scalability and stability here on my blog: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html

鉴于ra te你打开和关闭套接字(每秒一次会导致240(60 * 4)个套接字位于 TIME_WAIT 正常(4分钟)2MSL TIME_WAIT 期间)假设 TIME_WAIT 套接字在客户端而不是服务器上结束,这不应该证明太大问题并且假设您没有每秒连接到大量服务器,但是......如果您有许多客户端每秒都连接到您的服务器并且您没有确保您的服务器不会在中累积套接字TIME_WAIT 状态然后你可能会限制服务器的可扩展性。

Given the rate that you are opening and closing sockets (once a second would result in 240 (60*4) sockets sitting in TIME_WAIT in the normal (4 minute) 2MSL TIME_WAIT period) this shouldn't prove too much of a problem assuming the TIME_WAIT sockets ARE ending up on the client and not on the server and assuming you're not connecting to lots of servers every second, but... If you have many clients connecting to your server every second and you are not making sure that your server doesn't accumulate sockets in TIME_WAIT state then you may limit your server's scalability.

另一种方法是保持套接字连接打开,只有当它获得时才重新打开它破坏。对于您最初编程,这可能会稍微复杂一些,但以这种方式汇集连接可能会更加高效(当您需要发送数据时,您只需发送数据而不需要通过TCP握手来设置连接)并在客户端上提高资源效率;你永远不会在 TIME_WAIT 中持有240个插座......

The alternative is to hold the socket connection open and only reopen it if and when it gets disrupted. This may prove slightly more complex for you to initially program but pooling the connection in this way is likely to be considerably more efficient (when you DO need to send data you just send the data and don't need to go through the TCP handshake to set the connection up) and much more resource efficient on the client; you're not perpetually holding 240 sockets in TIME_WAIT...

这篇关于插座在1秒内打开和关闭或保持打开状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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