我目前正在开发android和服务器之间的套接字通信,这是一个在终端中运行的简单java程序。一切进展顺利,只是当我关闭应用程序时,logCat 中总是出现一条警告:
IInputConnectionWrapper showStatusIcon on inactive InputConnection
我正在互联网上搜索以找出问题,我在 StackOverflow 中找到了一个帖子 Similar Problem 。不同的是我可以在我的程序中很好地发送和接收信息。这个类似问题的答案是连接没有关闭。这是否意味着我在操作后没有调用 socket.close();
?这导致了更复杂的实现问题。
首先,我想要一个静态套接字来监听并将其发送到服务器。因为我可能不会每次传输东西时都关闭套接字,所以我只是在监听器完成工作后关闭它。
详细代码如下
我在构造函数中将连接初始化为:
client = new Socket(mServerName, mport);
out = new DataOutputStream(client.getOutputStream());
inFromServer = new InputStreamReader(client.getInputStream());
reader = new BufferedReader(inFromServer);
并让他们在整个过程中都在场。
我将从 android 到服务器的传输写入到一个函数中,如下所示:
public void sendRequest(int type, int what1, int what2, Object data)
{
try{
if(client.isConnected())
{
out.writeUTF(encoded(type,what1,what2,data) + "\n");
}
}catch(IOException e){
Log.e(TAG, "IOException at SendRequest");
e.printStackTrace();
}
}
新线程中的监听器:
try {
String line = null;
while ((line = reader.readLine()) != null)
{
ReceiveHandler(line);
}
} catch (IOException e) {
Log.e(TAG, "IOException at StartListen");
e.printStackTrace();
}finally{
try {
// The Only Place that I close the Socket
inFromServer.close();
out.close();
reader.close();
client.close();
} catch (IOException e) {
Log.e(TAG, "Close Socket with IOException " + e.toString());
e.printStackTrace();
}
}
我的问题是:
Is there something wrong with my implementation or are there better ways to do this?
非常感谢您的帮助!
最佳答案
有一个工具可以帮助您诊断 Android 设备和模拟器上的网络相关问题。它可能会帮助您进一步追踪问题。 ARO 工具是开源的,可在此处获取 http://developer.att.com/developer/forward.jsp?passedItemId=9700312
关于java - Android 中的发送和接收套接字实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11183342/