简体   繁体   English

可中断套接字读取 Java

[英]Interruptible Socket Read Java

I'm trying to create a fairly simple client/server application in java.我正在尝试用 Java 创建一个相当简单的客户端/服务器应用程序。 The client has two threads and the server has two threads (per client), one for input and output.客户端有两个线程,服务器有两个线程(每个客户端),一个用于输入和输出。 I am sending data both ways pretty much constantly over Object Streams.我通过对象流不断地双向发送数据。 Read() blocks. Read() 块。 I need to be able to interrupt the read() thread (ie to disconnect).我需要能够中断 read() 线程(即断开连接)。 How do I do this?我该怎么做呢?

Shutdown the socket for input.关闭输入插座。 This will cause the blocked read to throw EOFException , whereupon it should close the socket and exit the thread.这将导致被阻塞的读取抛出EOFException ,因此它应该关闭套接字并退出线程。

Close the Socket , and the read method will be interrupted with a IOException .关闭Socketread方法将被IOException中断。 Handle that exception to clean up your thread.处理该异常以清理您的线程。

You can either use non blocking calls or use Interrupt method on the thread.您可以在线程上使用非阻塞调用或使用中断方法 Once interrupted, the read operation will throw an Exception which you can catch and end the thread nicely.一旦中断,读取操作将抛出一个异常,您可以很好地捕获并结束线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM