[英]Android client/Java server socket; android sending but not receiving?
我一直在寻找四个小时,这让我疯了。 如果你需要更多信息/代码问我会编辑,我会试着保持这个简短。
所以我有一个Android客户端,使用PrintWriter和BufferedReader连接到服务器。 它的工作方式是启动一个新的ASyncTask()来加载连接。 建立连接后,它会向服务器发送一条“Join”消息,然后加载一个监听线程,该线程有一个等待UserInput.readLine()!= null的while循环,一旦打破它就会返回一个运行一个进程的字符串获取字符串并执行操作的函数,并重新加载侦听任务。
//Listener thread
class listen extends AsyncTask<Integer, Integer, Void> {
@Override
protected Void doInBackground(Integer... params) {
//Disconnect variable that's only turned true on backpress
if (!disconnect) {
try {
message = Connection.listen(); //socket object
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// async task finished
if (!disconnect) {
say("INCOMMING"); //easy-made function for Toast
input(message);
}
}
}
在那个连接中:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
}
return userInput;
}
现在在我的服务器java应用程序中,我有一个线程将其他连接线程加载到ArrayList中,并充当总部将消息分发给所有子客户端
在我的联系中:
while ((inputLine = in.readLine()) != null) {
//Tells HQ to process string, with id being who it's coming from
hq.Process(id, inputLine);
if (!connected)
break;
}
在HQ对象中:
public void Process(int id, String str) {
String[] msg = str.split(","); //split message
String send = " "; //string I print to console
if (msg[0].equals("join")) {
send = msg[1] + " has joined!";
parent.seats[cnew.get(id).seat] = id;
cnew.get(id).sendData();
System.out.println(id);
}
加入后,HQ告诉该连接将该播放器的信息发送到手机
public void sendData() {
out.println("chips," + chips); // Update chip count
//give player his cards
out.println("card," + hq.parent.gameCards.getCard(10) + ","
+ hq.parent.gameCards.getCard(11));
//a cry for help to get some output on the phone
out.println("error,SAY THIS");
// out.flush(); //commented out because it didn't help at all
System.out.println("sending id " + id); //debug checker (ignore this)
}
我的问题是,当我连接四部手机并且他们都互相发送祝酒时,它有效。 但是一旦我改变它以便在玩家加入后立即发回数据,我根本就没有得到Android的响应。
我无法弄清楚为什么它不起作用。 在服务器端,它正在通过所有内容(使用system.prints检查)。 建立了连接,当我点击手机上的按钮时,服务器正在输出它的响应。 但手机没有收到任何东西 - 我仍然不知道服务器是否无法发送或手机无法读取。 您能在代码中看到可能导致此问题的任何内容吗? 需要看更多? 或者有关于如何调试连接状态的任何提示? listen()任务永远不会完成它的执行。
更新:所以我发现它可能与我在android端的while()循环有关,doh,可能永远不会破坏。 愚蠢的错误。 但我试图将其添加为测试人员,但仍然没有:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
if (userInput.length() > 2)
break;
}
return userInput;
}
更新:下一次绝望的更新 - 当我点击“返回”(它将退出消息发送到关闭连接的服务器,并调用out.close和rest.close)然后我得到一个永无止境的“MSG”Toast循环 - Toast当输入被识别时我放了。 out.close会导致阻塞吗?
事实证明,服务器端的println没有打印新行 - 在服务器消息结束时添加+“\\ n”使其通过。 为什么? 我不知道..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.