SocketException 连接重置

发布于 2024-11-18 06:22:39 字数 230 浏览 5 评论 0原文

我创建了一个接受 TCP 连接的服务器。连接到套接字后,它循环从输入流读取数据。

步骤:

  1. 我启动了我的服务器。
  2. 启动客户端。

现在我正在关闭客户端。

然后服务器给我 SocketException Connection Reset

在从输入流读取之前如何检查我的客户端是否处于活动状态。

I created a server which accept TCP connection . After connected to socket it looping for reading data from input stream.

Steps:

  1. I started my server.
  2. Start Client.

Now I am closing client.

Then Server gives me SocketException Connection Reset

How do I check that my client is alive or not before reading from input stream.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

Bonjour°[大白 2024-11-25 06:22:39

如果您的服务器收到“连接重置”,它可能正在写入已被另一端关闭的连接。用户按下“后退”按钮的浏览器就是一个很好的例子。如果这是预期情况,请忽略该异常。如果构成应用程序协议错误,请调试应用程序。

If your server gets a 'connection reset' it is probably writing to a connection that has already been closed by the other end. A browser whose user presses the 'back' button is a good example. If this is an expected condition, ignore the exception. If it constitutes an application protocol error, debug the application.

德意的啸 2024-11-25 06:22:39

有两种方法可以检查套接字是否已连接,您可以读取或写入它,如果已连接,则不会收到错误,如果未连接,则会收到错误。这就是我检查套接字是否已连接的方式:

BufferedReader reader;

public void run()
{
    try
    {
        String message;
        while((message = reader.readLine())!=null) //The thread stops here untill the reader has somthing to read
        {
            System.out.println(message);
        }
     }catch(Exception e)
     {
         System.out.println("Client disconnected!");
         // an error is thrown when reader cannot read the stream because it is closed, you will get a connection reset error.
     }
}

当套接字连接时,读取器会等待,直到有东西要读取(message = reader.readLine())。当客户端断开连接并且 Socket 关闭时,读取器会抛出异常,因为流已关闭,因此没有任何内容可以读取。我希望这有帮助!

There are 2 ways you can check if a socket is connected, you can either read or write to it, if it is connected you wont get an error, if it isnt connected you will get an error. This is how i check if a socket is connected:

BufferedReader reader;

public void run()
{
    try
    {
        String message;
        while((message = reader.readLine())!=null) //The thread stops here untill the reader has somthing to read
        {
            System.out.println(message);
        }
     }catch(Exception e)
     {
         System.out.println("Client disconnected!");
         // an error is thrown when reader cannot read the stream because it is closed, you will get a connection reset error.
     }
}

When the Socket is connected the reader waits untill there is somthing to be read(message = reader.readLine()). When the client disconnects and the Socket is closed, the reader throws an exception because there is nothing that can be read because the stream is closed. I hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文