我正在開發此應用程序,我需要在某些時候發送數據(主要是雙打和字符串)到服務器。 我將使用TCP套接字和DataOutput/InputStreams。我想知道什麼是最好的方法來做到這一點。我應該有一個單獨的類來處理與實施的寫/讀方法的連接,或者可能只是在onCreate()的主Activity類中定義套接字/流等? 第一種方式甚至可能嗎?任何例子,將不勝感激。正確的方式在Android應用程序中使用套接字
ps。我應該使用不同的線程來處理連接嗎?
編輯。
所以,如果我得到它的權利,這應該是正確的:
public class ConnectionHandler extends AsyncTask<Void, Void, Void>{
public static String serverip = "192.168.1.100";
public static int serverport = 7777;
Socket s;
public DataInputStream dis;
public DataOutputStream dos;
public int message;
@Override
protected Void doInBackground(Void... params) {
try {
Log.i("AsyncTank", "doInBackgoung: Creating Socket");
s = new Socket(serverip, serverport);
} catch (Exception e) {
Log.i("AsyncTank", "doInBackgoung: Cannot create Socket");
}
if (s.isConnected()) {
try {
dis = (DataInputStream) s.getInputStream();
dos = (DataOutputStream) s.getOutputStream();
Log.i("AsyncTank", "doInBackgoung: Socket created, Streams assigned");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("AsyncTank", "doInBackgoung: Cannot assign Streams, Socket not connected");
e.printStackTrace();
}
} else {
Log.i("AsyncTank", "doInBackgoung: Cannot assign Streams, Socket is closed");
}
return null;
}
public void writeToStream(double lat, double lon) {
try {
if (s.isConnected()){
Log.i("AsynkTask", "writeToStream : Writing lat, lon");
dos.writeDouble(lat);
dos.writeDouble(lon);
} else {
Log.i("AsynkTask", "writeToStream : Cannot write to stream, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "writeToStream : Writing failed");
}
}
public int readFromStream() {
try {
if (s.isConnected()) {
Log.i("AsynkTask", "readFromStream : Reading message");
message = dis.readInt();
} else {
Log.i("AsynkTask", "readFromStream : Cannot Read, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "readFromStream : Writing failed");
}
return message;
}
}
,我會用這樣的事情在我的活動類:
ConnectionHandler conhandler = new ConnectionHandler();
conhandler.execute();
conhandler.writeToStream(lat , lon);
好啊,我在想更多的傳統線程,我會更多地看AsyncTask,並會回來,如果我有任何問題。 謝謝。 – kotsosh 2011-03-24 21:55:32
我也剛剛爲任何感興趣的人發現這個例子:http://stackoverflow.com/questions/5135438/example-android-bi-directional-network-socket-using-asynctask – kotsosh 2011-03-24 22:02:40