你如何处理Java中的Socket Disconnecting? [英] How do you handle Socket Disconnecting in Java?

查看:116
本文介绍了你如何处理Java中的Socket Disconnecting?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿所有人。我有一个使用ServerSocket和Socket类用java编写的服务器。



我希望能够检测并处理断开连接,然后在必要时重新连接新客户端。



检测客户端断开连接,关闭套接字,然后接受新客户端的正确步骤是什么?

解决方案

据推测,你是从套接字读取,可能使用输入流上的包装器,例如BufferedReader。在这种情况下,当相应的读操作返回-1(对于原始read()调用)或null(对于readLine()调用)时,可以检测到流结束。



某些操作在关闭的套接字上执行时会导致SocketException,您还需要适当处理。


Hey all. I have a server written in java using the ServerSocket and Socket classes.

I want to be able to detect and handle disconnects, and then reconnect a new client if necessary.

What is the proper procedure to detect client disconnections, close the socket, and then accept new clients?

解决方案

Presumably, you're reading from the socket, perhaps using a wrapper over the input stream, such as a BufferedReader. In this case, you can detect the end-of-stream when the corresponding read operation returns -1 (for raw read() calls), or null (for readLine() calls).

Certain operations will cause a SocketException when performed on a closed socket, which you will also need to deal with appropriately.

这篇关于你如何处理Java中的Socket Disconnecting?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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