如果服务器端口错误,客户端正在等待响应
客户端输入有关服务器的一些信息(例如服务器名称、端口号...)以及将发送的消息。但如果端口号写错了,客户端仍然等待响应。
如果目标服务器未打开端口,如何抛出异常?
The client enters some information about server (such as server name, port number vs...) and the message which will be sent. But If it writes port number wrong, the client still waits for response.
How can I throw an exception if the port is not opened for the destination server ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果服务器未侦听某个端口,它将收到
ConnectException: 连接被拒绝
但是,如果您连接到正在运行不同服务的端口,它可能不会收到响应,具体取决于该服务的功能。如果这是一个问题,我建议您在未获得预期结果时超时连接。If the server is not listening on a port it will get a
ConnectException: Connection refused
However if you connect to a port which is running a different service, it may not get a response depending on what that service does. If this is a concern, I suggest you time-out the connection if it doesn't get an expected result.@skaffman的评论是正确的。
通常,当您尝试打开到没有任何监听的端口的 TCP/IP 连接时,远程计算机上的 TCP/IP 堆栈会通过发送 RST 来响应初始 SYN 消息,这会导致“连接被拒绝”例外。
如果您没有看到此异常,最可能的原因是某些东西阻止了 SYN 消息(或正常的 SYNACK 响应)。这通常是防火墙(在任一端)。常见的防火墙策略是默默地丢弃除少数端口之外的所有端口的 TCP SYN 消息。这将产生您观察到的效果。
无论哪种方式,您都无法立即获得例外。您能做的最好的事情就是设置一个非零的连接超时,并捕获超时异常
@skaffman's comment is right.
Normally, when you attempt to open a TCP/IP connection to a port that nothing is listening on, the TCP/IP stack on the remote machine responds to the initial SYN message by sending an RST, and this results in a "connection refused" exception.
If you are not seeing this exception, the most likely cause is that something is blocking the SYN message (or the normal SYNACK response). This will typically be a firewall (at either end). A common firewall strategy is to silently drop TCP SYN message for all but a small number of ports. This will have the effect that you observe.
Either way, there is nothing you can do to get an immediate exception. The best you can do is to set a non-zero connection timeout, and catch the timeout exception