Java设置Client Socket链接Server超时时间
2016-09-10 12:03
946 查看
一、错误示例
最近在写socket程序时,偶然发现程序被卡住很长时间,调试后发现是创建Socket时,采用的方式不对:Socket s = new Socket(String host, String port);
当采用该方式创建
Socket时,默认的链接超时时间为0(A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.),也就意味着链接永不超时,直到发生链接超时异常,所以程序会被卡住,并最终抛出异常。
二、正确示例
若要设置链接超时,需要使用如下方式创建Socket:
Socket s = new Socket(); SocketAddress socketAddress = new InetSocketAddress(serverIp, port); s.connect(socketAddress, timeout);
其中
timeout就是设置的超时时间,当超时时间到时会抛出
SocketTimeoutException而不会无限等待的去尝试链接。
附
设置从Socket读取数据超时
通过Socket方法
setSoTimeout(int timeout),Javadoc关于该方法的的说明如下:
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
相关文章推荐
- Java设置Client Socket链接Server超时时间
- php同时作为server端和client端(soapclient)的超时时间设置小结
- Socket Java设置超时时间
- Socket Java设置超时时间
- 来段代码提提神-Java实现SocketServer和client链接
- Java爬虫(六)-- httpClient进阶:超时时间设置+cookie保存策略
- 关于http socket timeout 超时时间 未设置 导致线程一直在等待(线程饥饿),微信公众号开发过程遇到的。java
- 关于http socket timeout 超时时间 未设置 导致线程一直在等待(线程饥饿),微信公众号开发过程遇到的。java
- Java基础网络---2-----连接到服务器(设置链接超时时间)
- [转]socket的send、recv阻塞设置阻塞超时时间
- java 设置socket连接超时
- java设置一段代码执行的超时时间的简单方法 间接实现获取Connection超时问题
- socket的send、recv阻塞设置阻塞超时时间
- [Java] Netty Websocket Server Javascript Client
- java socket的超时设置
- 基于XSocket框架的socket编程技巧(设置连接的超时时间和最大空闲时间)
- tomcat链接mysql时超时报错java.io.EOFException: Can not read response from server. Expected to read 4 bytes,
- java socket client to python server with utf-8
- Android Socket通信如何设置超时时间
- 设置socket connect 超时时间