全部产品
物联网行业方案

java_net_SocketTimeoutException

更新时间:2018-04-19 17:13:30

问题分析:

这类异常发生在建立socket连接或读取数据时发生超时时抛出。

解决方案:SocketTimeoutException发生在socket连接过程中的accept()和read()中,服务端或客户端设置超时连接后,当到达超时时间均会抛出此类异常。建议设置可接受的socket超时时间并捕获处理SocketTimeoutException。

代码示例:

服务器端:

  1. ServerSocket serverSocket = null;
  2. try {
  3. serverSocket = new ServerSocket(8111);
  4. serverSocket.setSoTimeout(10000);
  5. while (true) {
  6. try {
  7. Socket clientSocket = serverSocket.accept();
  8. BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  9. System.out.println("Client said :"+ inputReader.readLine());
  10. } catch (SocketTimeoutException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. } catch (IOException e1) {
  15. e1.printStackTrace();
  16. } finally {
  17. try {
  18. if (serverSocket != null) {
  19. serverSocket.close();
  20. }
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }

客户端:

  1. @Override
  2. public void run() {
  3. try {
  4. HttpURLConnection.setFollowRedirects(false);
  5. HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
  6. con.setRequestMethod("HEAD");
  7. con.setConnectTimeout(5000);
  8. log.info("Response Code: " + con.getResponseCode());
  9. } catch (SocketTimeoutException e) {
  10. System.out.println(“SocketTimeoutException”+e.getMessage());
  11. } catch (IOException e) {
  12. System.out.println(“IOException”+e.getMessage());
  13. } catch (Exception e) {
  14. System.out.println(“Exception”+e.getMessage());
  15. }
  16. }

参考文献:

1.https://developer.android.com/reference/java/net/SocketTimeoutException.html

2.https://examples.javacodegeeks.com/core-java/net/sockettimeoutexception/java-net-sockettimeoutexception-how-to-solve-sockettimeoutexception/