我创建了一个客户端-服务器应用程序,双方使用套接字连接和输入/输出流进行通信以发送/接收数据。这一切都很好,但前提是我只有一个使用连接的活动。由于我的应用程序中将有不止一个活动,并且经过一番搜索,我得出结论,我必须创建一个服务来处理套接字连接并从套接字流发送/接收。我以前从未使用过服务,我想我会一步一步开始。目前我刚刚创建了一个服务,它创建了我的客户端类的一个实例(它扩展了线程)并启动了该线程,它建立了与服务器的连接。
我的客户类
T_Client:
public class T_Client extends Thread {
private static final String TAG = "T_Client";
private static String serverIP = "192.168.2.3";
private static int port = 4444;
private InetAddress serverAddr = null;
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private Object objIn;
public void send(MessageCustom _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
Log.i("Send Method", "Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e("Send Method", ex.toString());
}
}
}
public void stopClient() {
Log.v(TAG,"stopClient method run");
running = false;
}
@Override
public void run() {
running = true;
try {
serverAddr = InetAddress.getByName(serverIP);
Log.i("TCP Client", "C: Connecting...");
sock = new Socket(serverAddr, port);
try {
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
Log.i(TAG, "C: Connected.");
while (running) {
objIn = in.readObject();
Log.i("Object Read Class", objIn.getClass().toString());
Log.i("Object Read", objIn.toString());
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn + "'");
} catch (Exception e) {
Log.e(TAG, "S: Error", e);
} finally {
out.close();
in.close();
sock.close();
Log.i(TAG, "Closing socket: " + sock);
}
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
}
}
}
我的服务类
MyService:
public class MyService extends Service {
private static final String TAG = "MyService";
private T_Client client;
@Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
if (client != null) {
try {
client.stopClient();
} catch (Exception e) {
Log.e(TAG, "Error on close: " + e);
}
}
super.onDestroy();
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand");
client = new T_Client();
client.start();
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
我目前在主要活动中所做的只是使用开始和停止按钮来启动/停止服务
public void start(View v){
Log.i(TAG,"Start pressed");
Intent intent=new Intent(getBaseContext(),MyService.class);
startService(intent);
}
public void stop(View v){
Log.i(TAG,"Stop pressed");
Intent intent=new Intent(getBaseContext(),MyService.class);
stopService(intent);
}
所以我的问题是:
- 我需要做什么才能使用我的服务发送内容?
- 如何处理从服务器读取的对象,以便让应用程序实时知道已收到某些内容?
非常感谢任何可以指导我解决问题的意见。
先感谢您。