请在下面的代码中帮助我。它抛出错误:Android socket:buffer为null。你能告诉我出了什么问题吗?
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();
}
答案 0 :(得分:1)
byte[] buffer = null;
int is=socket.getInputStream().read(buffer, 0, 1024);
无效,因为您没有为.read()方法分配缓冲区来存储结果 - 实际上您已将其显式设置为null。
您需要执行诸如
之类的操作 byte[] buffer = new byte[1024];
实际分配你的缓冲区。
答案 1 :(得分: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
}
}
});
}
};
答案 2 :(得分:0)
out.write(("285|SIP|0200|**4536780670138355*000000*1000***1309181650****000094*130918165044**1408***0918*****901301654144**300*************000000023834****00400013*65432100400013 ******P920035595*952*******************************************************************************").getBytes());
之后
写:
socket.shutdownOutput();