[英]Android Java - Two socketmessages when sending one
I send a message over sockets from an android app to a java program. 我通过套接字从Android应用程序向Java程序发送消息。 This message is sent with a printwriter.
该消息与印刷机一起发送。
here is how I send my message from android to java program: 这是我从Android向Java程序发送消息的方式:
out.println("Hello there");
out.flush();
This is how I receive the message: 这是我收到消息的方式:
while(true){
String msg = in.readLine();
System.out.println("MSG: " + msg);
...some if-statements...
}
The output of the System.out.println is: MSG: Hello there * MSG: null * System.out.println的输出是: MSG:您好,那里 * MSG:null *
How come I get null there? 我怎么会在那里变成零? I'm only sending "hello there"..
我只发送“你好,那里”。
Help would be appreciated, thanks! 帮助将不胜感激,谢谢!
EDIT: Actual code of the java program. 编辑: Java程序的实际代码。
while (run) {
String msg = in.readLine();
String[] parts;
String username;
String password = null;
System.out.println("MSG: " + msg);
parts = msg.split("\\*");
username = parts[0];
password = parts[1];
boolean validUser = false;
validUser = db.authenticate(username, password);
if (validUser) {
db.updateIP(username, socket.getInetAddress().getHostAddress());
out.println("done");
out.flush();
} else {
out.println("loginfail");
out.flush();
closeSocketConnection();
}
}
}
private void closeSocketConnection() throws IOException {
in.close();
out.close();
socket.close();
run = false;
}
What is your exit condition for your while
loop? while
循环的退出条件是什么?
It looks to me like it is repeating and readLine
will return null
when the end of the stream has been reached causing MSG: null
to be printed. 在我看来,它正在重复,并且在到达流的末尾并导致
MSG: null
被打印时, readLine
将返回null
。
Updated given new information: 更新了给定的新信息:
Assuming user*123
is a valid username/password combo then closeSocketConnection()
is never called, the loop returns to the top, readLine
returns null
and you see your erroneous output. 假设
user*123
是有效的用户名/密码组合,则永不调用closeSocketConnection()
,循环返回到顶部, readLine
返回null
,您会看到错误的输出。 Followed by a NullPointerException
on parts = msg.split("\\\\*");
在
parts = msg.split("\\\\*");
后跟NullPointerException
Your loop should read: 您的循环应显示为:
while ((line = in.readLine()) != null)
{
// ...
}
At the moment you're processing the null that indicates end of stream inside the loop, hence you're printing it as a message when it isn't. 目前,您正在处理表示循环内流结束的null,因此,如果没有,则将其打印为消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.