你如何处理 Java 中的套接字断开连接? [英] How do you handle Socket Disconnecting in Java?

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

问题描述

大家好.我有一个使用 ServerSocket 和 Socket 类用 Java 编写的服务器.

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?

推荐答案

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

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).

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

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

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

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