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 ?
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'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
精彩评论