[英]Java Socket - how to catch Exception of BufferedReader.readline()
I have a Thread (let's say T1) which reads data from socket: 我有一个Thread(假设是T1)从socket读取数据:
public void run() {
while (running) {
try {
BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream()) );
String input = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Another Thread (lets say T2) try to finish the program in one of its method. 另一个线程(比方说T2)尝试在其中一个方法中完成程序。 Therefore T2 does the following:
因此T2执行以下操作:
T1.running = false;
socket.close();
Here is this scenario for which i couldn't find a solution: 这是我无法找到解决方案的场景:
PS: "Another question about the Thread Debugging" PS:“关于线程调试的另一个问题”
Normally when i debug the code step by step, i lose the 'active running line' on a context switch. 通常,当我逐步调试代码时,我在上下文切换上丢失了“活动运行线”。 Let's say i'm in line 20 of T1, context switch happens, let's assume the program continues from the 30.line of T2, but the debugger does not go/show to the 30.line of T2, instead the 'active running line' vanishes.
假设我在T1的第20行,发生上下文切换,让我们假设程序从T2的30.line继续,但是调试器不会显示/显示到T2的30.line,而是'active running line '消失了。 So i lose the control over the code.
所以我失去了对代码的控制权。 I use Eclipse for Java and Visual Studio for C#.
我使用Eclipse for Java和Visual Studio for C#。 So what is the best way to track the code while debugging on a context switch ?
那么在上下文切换时调试时跟踪代码的最佳方法是什么?
For your problem assuming you are using a Thread Pool maybe you should make a ThreadFactory that installs a Thread.UncaughtExceptionHandler on all Threads and then invoke your work with execute() on the ExecutorService instead of submit(). 对于你的问题,假设你正在使用一个线程池,你可能应该创建一个ThreadFactory,在所有线程上安装一个Thread.UncaughtExceptionHandler,然后在ExecutorService上调用execute()而不是submit()。
For you problem with debugging maybe you should read http://msdn.microsoft.com/en-us/library/ms164746.aspx 对于调试问题,您可以阅读http://msdn.microsoft.com/en-us/library/ms164746.aspx
Your code has several other problems so I'll address them all at the same time. 您的代码还有其他几个问题,所以我会同时解决所有这些问题。
BufferedReader
outside the loop. BufferedReader
。 Otherwise you will lose data in the buffers being discarded each time around the loop. readLine()
for null. readLine()
的结果为null。 If you get it, you must close the BufferedReader
and exit the loop. BufferedReader
并退出循环。 BufferedReader
and exit the loop. BufferedReader
并退出循环。 What i want is to catch this SocketException.
我想要的是捕获这个SocketException。
So catch it. 抓住它吧。
I can't put a try/catch(SocketException) in T1.run().
我不能在T1.run()中放置try / catch(SocketException)。
You must. 你必须。 No choice.
没有选择。 You have to completely rewrite it anyway because of the above items.
由于上述条款,你必须完全重写它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.