套接字长读数据

时间:2011-05-23 09:17:55

标签: java android sockets

这是我的代码:

private String receiveData(String sjson) {
        Log.i(TAG,"send request: " + sjson);
        String jstr="";
        try {
            OutputStream out = s.getOutputStream();
            out.write(sjson.getBytes());
            out.flush();
            //out.close();
            Log.v(TAG,"sended data");
            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
            char[] cbuf = new char[1];
            input.read(cbuf);                   
            String size = new String(cbuf);
            while (input.read(cbuf) != 0) {
                if((new String(cbuf)).equals("{") == true) 
                    break;
                size = size + new String(cbuf);
            }
            char[] jbuf = new char[Integer.valueOf(size)];
            input.read(jbuf);
            jstr = "{" + new String(jbuf);
        }catch (Exception e) {
            Log.e(TAG,e.toString());
        }
        Log.d(TAG,"responce: " + jstr);
        return jstr;
    }

    public void connectSocket() {
        Log.v(TAG,"connecting Socket: "+URL+":"+PORT);
        try {
            s = new Socket(URL, PORT);
            Log.v(TAG,"connect Socket!");
            ERROR_CODE = 0;
        }catch (Exception e) {
            Log.e(TAG,e.toString());
            ERROR_CODE = ERROR_SOCKET_CONNECT_SUCCESSFULL;
        }
        Log.e(TAG,getErrorMsg(ERROR_CODE));
    }

    public void closeSocket() {
        Log.v(TAG,"closeSocket");
        try {
            s.close();
        }catch (Exception e) {
            Log.e(TAG,e.toString());
        }
    }

在服务器上,答案不到一秒钟。在客户端,它在读取数据前经过1分钟。

应用程序停留在input.read(cbuf);等待回答。

日志:

05-23 06:35:17.540: VERBOSE/Utilits(358): Auth: 77.221.129.100:10598
05-23 06:35:17.660: INFO/Utilits(358): send request: 0119{"data":{"password":"12345","imei":"000000000000001"},"method":"login"}
05-23 06:36:17.909: DEBUG/Utilits(358): responce: {"response":{"success":true,"user":{"id":"6","properties":{"auto":"model":"audi","color":"ffff","number":"td123r"}},"is_driver":"1"}}}

为什么阅读答案需要这么长时间?

1 个答案:

答案 0 :(得分:1)

您希望这种方法做什么?它有bug,它会做它应该做的事情。

  • 您应该在创建InputStreamReader时指定encoding / charset
  • 为什么你从头到尾逐字逐句地阅读“{”
  • 为什么要在点击“{”
  • 之前为每个字符创建一个字符串
  • 为什么要在循环中追加字符串?如果必须附加,请使用StringBuilder。
  • input.read返回一个整数,表示您收到的字节/字符数 它永远不能保证它会填充缓冲区。所以你可能无法获得所有数据。
  • 你为什么不关闭资源?

..现在为什么它可能会很慢。服务器是否正在刷新数据?如果没有,请确保服务器正在刷新数据。