我正在开发此应用程序,我需要在某些时候发送数据(主要是双打和字符串)到服务器。 我将使用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