1
我正在測試項目,就像使用Wi-Fi連接的基本聊天程序。 我創建套接字來連接兩個不同的設備,但我的問題是,當我發送第一條消息時,它顯示在另一個設備上。但是如果我嘗試再次發送,我可以在第一個日誌中看到該消息已發送,但從未在第二個設備中顯示。Android AsyncTask使用套接字發送/讀取數據
我試圖在另一個線程中執行讀取接收到的數據或在異步任務中,但問題仍然存在。下面是我實現的兩種方式:
單線程:
public void listenForSocket(){
thread = new Thread(new Runnable() {
public void run() {
Log.e("READDATAFROMSOCKET","READDATAFROMSOCKET");
try {
// sets the service running state to true so we can get it's state from other classes and functions.
serverSocket = new ServerSocket(DNSUtils.port);
client = serverSocket.accept();
client.setKeepAlive(true);
InputStream is = client.getInputStream();
Log.d("","is Size : "+is.available());
BufferedReader in = new BufferedReader(new InputStreamReader(is));
int readed = in.read();
Log.d("","readed bytes : "+readed);
String line = "";
while ((line = in.readLine()) != null) {
Log.i("","line : "+line);
changeText(line);
}
//client.close();
//serverSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
而這裏的AsyncTask:
class ServerTask extends AsyncTask<Void, Void, Void>{
private String line = "";
@Override
protected Void doInBackground(Void... params) {
try {
Log.e("ASYNCTASK","ASYNCTASK");
// sets the service running state to true so we can get it's state from other classes and functions.
serverSocket = new ServerSocket(DNSUtils.port);
client = serverSocket.accept();
client.setKeepAlive(true);
InputStream is = client.getInputStream();
Log.d("","is Size : "+is.available());
BufferedReader in = new BufferedReader(new InputStreamReader(is));
int readed = in.read();
Log.d("","readed bytes : "+readed);
while ((line = in.readLine()) != null) {
Log.i("","line : "+line);
}
//client.close();
//serverSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
changeText(line);
}
}
changeText(字符串); -
private void changeText(final String line) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout.LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
TextView sendMsg = new TextView(MainActivity.this);
sendMsg.setText(DNSUtils.clientName+" : "+line);
sendMsg.setTextColor(Color.DKGRAY);
sendMsg.setTextSize(18);
layout.addView(sendMsg, params);
}
});
}
任何想法如何解決這個問題?
而另一個問題是,當我讀取收到的數據時,發送的字符串的第一個字母從不顯示。它總是從第二個字母開始。
在此先感謝。
我認爲後臺服務更符合您的需求。只要您的「活動」與其綁定,它就會保持活力。它在完成代碼後不會完成,比如你的'Threads'或'AsyncTasks' – tolgap 2012-07-30 15:38:07