套接字异常:套接字已关闭 [英] Socket Exception: socket is closed

查看:178
本文介绍了套接字异常:套接字已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建能够与多个客户端连接的服务器.我的主要功能是:

I want to create server which is able to be connected with multiple clients. My main function is:

ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(5556);
    } catch (IOException ex) {
        Logger.getLogger(MakaoServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    while (true) {
        try {
            Socket connection = serverSocket.accept();
            PlayerConnection playerConn = new PlayerConnection(connection);
            playerConn.start();
        } catch (IOException ex) {
            System.out.println("Nie można było utworzyć gniazda.");
        }
    }

PlayerConnection 是一个线程类.运行方法:

PlayerConnection is a Thread class. The run method:

public void run() {
    InputStream input = null;
    while (true) {
        try {
            input = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String msg = reader.readLine();
            System.out.println(msg);

        } catch (IOException ex) {
            Logger.getLogger(PlayerConnection.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

        }
    }
}

当我运行客户端并向服务器发送消息时,它已收到但在下一次循环迭代 connection.getInputStream();抛出 Socket 异常 套接字已关闭.为什么?

When I run client and send message to server it's received but on the next while loop iteration connection.getInputStream(); throws an Socket Exception socket is closed. Why?

java.net.SocketException: socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:150)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at makaoserver.PlayerConnection.run(PlayerConnection.java:38)

推荐答案

将输入流和缓冲读取器置于循环之外.

Put the input stream and buffered reader outside the loop.

可能创建多个连接到同一个输入流的流会导致这种情况.

Possibly creating multiple stream connected to the same input stream is causing this.

这篇关于套接字异常:套接字已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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