Android serversocket仅在第一次运行时读取输入

时间:2015-05-08 13:53:33

标签: java android sockets server

我正在创建一个非常简单的多人安卓游戏。设备使用套接字/服务器套件彼此共享信息。编译后第一次运行程序运行正常,但如果我关闭应用程序并再次启动它,程序将无法运行。以下是服务器代码的片段:

public void listen() {
        try {
            /**
             * Creates a new server socket. By passing in 0, the device will select any
             * available port that is open. This makes it possible to avoid having to hardcode
             * the port.
             */
            if (serverSocket == null)
                serverSocket = new ServerSocket(0);

            // sets the port to the generated server port
            setLocalPort(serverSocket.getLocalPort());

            // run this until the program stops
            while (!stop) {
                // make the server socket listen for input
                setSocket(serverSocket.accept());
                Log.d(TAG, "Socket opened");

                // creates a buffered reader in order to read the input

                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                // listen for messages
                while(!Thread.currentThread().isInterrupted()) {
                    try {
                        // reads the line
                        String line;
                        line = input.readLine();

                        // if the line is not null then call onReceive
                        if (line != null) {
                            onReceive(line);
                            Log.d(TAG, "Received: " + line);
                        }
                        Log.d(TAG, "received something");
                    } catch (IOException e) {
                        Log.d(TAG, "Error");
                    }
                    break;
                }
                // close the input
                input.close();
                Log.d(TAG, "Socket closed");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

当代码工作时,我得到以下Logcat消息:

  

05-08 15:00:54.186 11947-11965 / com.example.trommemand.playerapp D / NET:套接字打开   05-08 15:00:54.186 11947-11965 / com.example.trommemand.playerapp D / NET:收到:好的   05-08 15:00:54.186 11947-11965 / com.example.trommemand.playerapp D / NET:收到的东西   05-08 15:00:54.186 11947-11965 / com.example.trommemand.playerapp D / NET:Socket closed

然而,当它不起作用时我只得到以下内容:

  

05-08 15:00:54.186 11947-11965 / com.example.trommemand.playerapp D / NET:套接字打开   05-08 15:00:54.186 11947-11965 / com.example.trommemand.playerapp D / NET:Socket closed

我怀疑问题是我无法关闭所有套接字。我试图关闭serversocket,但由于这一行而导致错误:setSocket(serverSocket.accept());

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

始终关闭finally块中的资源。 尝试关闭input.close块中的finally ...就像这样:

           finally { 

                    try {
                        input.close();

                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                 }

看看这是否有效..