0

请在下面的代码中帮助我。它抛出错误:Android 套接字:缓冲区为空。你能告诉我有什么问题吗?

 try {
                    socket = new Socket("217.16.10.21", 1991);
                    out = new PrintStream(socket.getOutputStream(), true);
                    out.write(("285|SIP|0200|**4536780670138355*000000*1000***1309181650****000094*130918165044**1408***0918*****901301654144**300*************000000023834****00400013*65432100400013 ******P920035595*952*******************************************************************************").getBytes());

            byte[] buffer = null;
            int is=socket.getInputStream().read(buffer, 0, 1024);
            socket.setSoTimeout(500);

            String message=new String(buffer, 0, is);
            //in = new BufferedReader(new InputStreamReader(is), 8192);
             out.close();

            //String message=in.readLine();
            textaff.setText(message);
            in.close();

            //socket.close();
            Toast.makeText(getApplicationContext(), " "+message, 2000).show(); 

         } catch (UnknownHostException e) {
             Toast.makeText(getApplicationContext(), "erreur"+e.getMessage(), Toast.LENGTH_LONG).show();
              e.printStackTrace();
         } catch (IOException e) {
             Toast.makeText(getApplicationContext(), "erreur 2 "+e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
             e.printStackTrace();
         }  
4

3 回答 3

1
      byte[] buffer = null;
      int is=socket.getInputStream().read(buffer, 0, 1024);

将不起作用,因为您没有为 .read() 方法分配缓冲区来存储结果 - 实际上您已将其显式设置为 null。

你需要做一些事情,比如

      byte[] buffer = new byte[1024];

实际分配你的缓冲区。

于 2013-09-23T14:34:09.680 回答
0

out.write(("285|SIP|0200|**4536780670138355*000000*1000***1309181650****000094*130918165044**1408***0918*****901301654144**300*************000000023834****00400013*65432100400013 ******P920035595*952*******************************************************************************").getBytes());

写:

socket.shutdownOutput();
于 2017-04-03T20:42:01.057 回答
0

使用此侦听器获取传入消息:

public Emitter.Listener handleIncomingMessages = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject data = (JSONObject) args[0];
                String message = null;
                String imageText;
                try {
                    message = data.getString("message").toString();
                  Log.v("messageeeeeeeeeee",message);

                } catch (JSONException e) {
                    // return;
                }

                addMessage(message);

                try {
                    imageText = data.getString("image");
                    addImage(decodeImage(imageText));
                } catch (JSONException e) {
                    //return
                }
            }
        });
    }
};
于 2016-09-26T10:32:01.367 回答