这两个套接字实现有什么区别吗? [英] Is there any difference between those two implementations on sockets?

查看:99
本文介绍了这两个套接字实现有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用TCP套接字创建了一个客户端/服务器应用程序,但客户端也常常 并且在读取来自其中的新消息时抛出连接超时服务器。

在两个应用程序中使用此:

I've made a client/Server app using TCP sockets, but clients stuck too often and they throw "Connection timed out" while reading for new messages from the Server.
On both apps im using this:

try{
   do{
     message=(String) input.readLine();

     System.out.println(message);

   }while(!message.equals("Disconnect"));
 }catch (IOException e) {
    System.out.println(e.getMessage());
 }



但是在我见过的例子中,这些是:


But at examples i've seen, the do these:

do{
  try{
     message=(String) input.readLine();

     System.out.println(message);

  }catch (IOException e) {
     System.out.println(e.getMessage());
  }
}while(!message.equals("Disconnect"));





使用尝试而不是使用尝试而不是尝试是否有任何重大区别在do {}内



我尝试过:



到现在为止我已经测试了两种方式,但我没有设法重新创建错误。



Is there any major difference to use "try" out of the "do{}while" than using "try" inside the "do{}while"?

What I have tried:

Until now i have tested both ways but i didnt managed to recreate the error.

推荐答案

是的,有区别。



在第一个代码块中,当尝试块出现错误时,退出do- while循环并进入 catch readLine 不再被调用,因为现在执行catch块之后的代码。



In第二个代码块,当 try 块出现错误时,你不会退出do-while循环(因为try-catch在循环中)。因此,如果出现错误,执行 catch 中的代码后,循环继续运行并且 readLine 获取再次执行。
Yes, there is a difference.

In the first code block, when there's an error in the try block, you exit the do-while loop and go into catch. readLine does not get called anymore, because the code that goes after the catch block gets executed now.

In the second code block, when there's an error in the try block, you do not exit the do-while loop (because try-catch is inside the loop). So, in case of an error, after the code in catch is executed, the loop continues to run and readLine gets executed again.


这篇关于这两个套接字实现有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆