我在我们的软件中有一个错误,当我收到连接超时时发生。这些错误是非常罕见的(通常是当我的连接被我们的内部网络丢弃时)。我怎样才能人为地产生这种效果来测试我们的软件呢?

如果重要,应用程序是用c++ /MFC编写的,使用CAsyncSocket类。

编辑:

我尝试使用一个不存在的主机,我得到套接字错误:

无效的参数

我的下一个尝试是使用Alexander的建议,连接到不同的端口,例如81(在我自己的服务器上)。这很有效。与断开连接完全相同(等待60秒,然后出错)。谢谢你!


当前回答

Depending on what firewall software you have installed/available, you should be able to block the outgoing port and depending on how your firewall is setup it should just drop the connection request packet. No connection request, no connection, timeout ensues. This would probably work better if it was implemented at a router level (they tend to drop packets instead of sending resets, or whatever the equivalent is for the situation) but there's bound to be a software package that'd do the trick too.

其他回答

您可以安装Microsoft Loopback驱动程序,它将为您创建一个单独的接口。然后,您可以在它上连接到您的某些服务(您自己的主机)。然后在网络连接中,你可以禁用/启用这样的接口…

我想提醒大家注意mitmproxy。

通过配置(取自他们的示例)200:b@100:dr,您将获得一个随机断开的连接。

最简单的方法是使用CurrPorts删除连接。

然而,为了单元测试你的异常处理代码,也许你应该考虑抽象你的网络连接代码,并编写一个存根、mock或decorator来按需抛出异常。然后,您将能够测试应用程序错误处理逻辑,而不必实际使用网络。

您可以使用Python REPL来模拟接收数据时的超时(即在连接成功建立之后)。只需要一个标准的Python安装。

Python 2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
>>> s.bind(('localhost', 9000))
>>> s.listen(0)
>>> (clientsocket, address) = s.accept()

现在它等待一个传入连接。将您想要测试的任何东西连接到localhost:9000。当你这样做时,Python将接受连接,accept()将返回它。除非您通过客户端套接字发送任何数据,否则调用方的套接字应该在下一次recv()期间超时。

软件解决方案怎么样:

在应用服务器上安装SSH服务器。然后,使用套接字隧道在您的本地端口和应用服务器上的远程端口之间创建一条链路。您可以使用ssh客户端工具来实现这一点。让您的客户端应用程序连接到映射的本地端口。然后,您可以随意打破套接字隧道来模拟连接超时。