Android套接字:服务器的答案在哪里?

时间:2013-07-16 07:17:59

标签: android sockets

我使用xbmc服务器。我使用套接字连接到服务器并创建一个JSON POST请求。 这是我的要求:

{
    "method": "XBMC.GetInfoBooleans",
    "id": "iPad~XBMC.GetInfoBooleans",
    "jsonrpc": "2.0",
    "params": {
        "booleans": [
            "Player.Paused",
            "Player.Playing"
        ]
    }
}

代码:

    try {
        InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
        socket = new Socket(serverAddr, SERVERPORT);

        if (socket.isConnected()) {

            Log.d(LOG_TAG, "Connect with server");

            try {

                JSONObject jsonObjectMain = new JSONObject();
                JSONObject jsonObjectAdd = new JSONObject();
                JSONArray jsonArray = new JSONArray();

                jsonArray.put("Player.Paused");
                jsonArray.put("Player.Playing");

                jsonObjectAdd.put("booleans", jsonArray);

                jsonObjectMain.put("method", "XBMC.GetInfoBooleans");
                jsonObjectMain.put("id", "iPad~XBMC.GetInfoBooleans");
                jsonObjectMain.put("jsonrpc", "2.0");
                jsonObjectMain.put("params", jsonObjectAdd);

                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                out.write(jsonObjectMain.toString());
                out.flush();

            } catch (Exception e) {
                e.printStackTrace();
            }

            String inputLine = null;
            String result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                Log.d(LOG_TAG, in.readLine());
                result = result.concat(inputLine);
                Log.d(LOG_TAG, result);

            }

        }

        else
            Log.d(LOG_TAG, "Unconnect");

    } catch (UnknownHostException e1) {
        e1.printStackTrace();
        Log.d(LOG_TAG, "Ошибка UnknownHostException");
    } catch (IOException e1) {
        e1.printStackTrace();
        Log.d(LOG_TAG, "Ошибка IOException");
    }

在日志中,我可以看到"Connect with server",但我看不到字符串"Result"。在Android清单中,我添加了所有权限。我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

while loop中你从流中读了两遍。可能您只收到一行,当您尝试读取第二行时,您将获得null或End of stream。将while更改为:

while ((inputLine = in.readLine()) != null) {
    Log.d(LOG_TAG, inputLine);
    result = result.concat(inputLine);
    Log.d(LOG_TAG, result);
}

此外,作为一项改进:您应该使用StringBuilder而不是连接字符串。