【发布时间】:2011-03-24 21:41:24
【问题描述】:
我正在开发这个应用程序,我需要在某些时候将数据(主要是双精度和字符串)发送到服务器。 我将使用 TCP 套接字和 DataOutput/InputStreams。我想知道这样做的最佳方法是什么。我是否应该有一个单独的类来处理与实现的写入/读取方法的连接,或者只是在 onCreate() 的主 Activity 类中定义套接字/流等? 第一种方法甚至可能吗?任何示例将不胜感激。
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;
}
}
我会在我的 Activity 类中使用这样的东西:
ConnectionHandler conhandler = new ConnectionHandler();
conhandler.execute();
conhandler.writeToStream(lat , lon);
【问题讨论】:
标签: android sockets android-asynctask