Login
点击button后,client发出信息给server,server执行sql语句,返回结果集,然后根据结果集判断,再把判断结果返回给client,client得到结果选择弹出提示信息,还是转到下一页。这个看似简单,实际上很复杂的过程是怎么实现的?
1.button的监听代码
private OnClickListener loginconn = new OnClickListener() {
public void onClick(View v) {
String username = edtUsername.getText().toString();
String password = edtPassword.getText().toString();
if (username.equals("") || password.equals("")) {
Toast.makeText(LoginActivity.this, R.string.non_empty, Toast.LENGTH_LONG).show();
return;
}
// connect to the server
new connectTask().execute("");
while(mTcpClient == null || !mTcpClient.isReady());
// sends the message to the server
if (mTcpClient != null) {
mTcpClient.sendMessage("LOGIN " + username + " " + password);
}
}
};
两个String存储username和password。如果为空提示。如果非空,调用继承于AsyncTask的connectTask.关于AsyncTask,这里有很好的讲解。
详解Android中AsyncTask的使用 - scott's blog - 博客频道 - CSDN.NET.开始后台监听,如果mTcpClient一直没有新的响应,一直while等待,一旦不为null,执行sendMessage。所以兵分两路,看看connectTask怎么后台监听,sendmessage执行什么
2.connectTask
public class connectTask extends AsyncTask<String, String, TCPClient> {
@Override
protected TCPClient doInBackground(String... message) {
// we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
@Override
// here the messageReceived method is implemented
public void messageReceived(String message) {
// this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
String[] sArray = values[0].split(" ");
if (sArray.length == 2) {
if (sArray[0].equals("OK")) {
// Toast.makeText(MainActivity.this, R.string.login_ok,
// Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this,
TabHostActivity.class);
Bundle bundle = new Bundle();
bundle.putString("session", sArray[1]);
intent.putExtras(bundle);
startActivity(intent);
mTcpClient.stopClient();
}
}
}
}
execute之后,异步任务马上开始,执行doInBackGround. 现在是两个异步任务开始执行,随意会感觉很乱。
package com.example.chatclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.util.Log;
public class TCPClient {
private String serverMessage;
public static final String SERVERIP = "175.159.81.76"; // your computer IP
// address
public static final int SERVERPORT = 4445;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out = null;
BufferedReader in;
/**
* Constructor of the class. OnMessagedReceived listens for the messages
* received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* @param message
* text entered by client
*/
public void sendMessage(String message) {
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient() {
mRun = false;
}
public boolean isReady()
{
return (out != null);
}
public void run() {
mRun = true;
try {
// here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
// create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
// send the message to the server
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
// receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// in this while the client listens for the messages sent by the
// server
while (mRun) {
serverMessage = in.readLine();
Log.e("TCP Client", serverMessage);
if (serverMessage != null && mMessageListener != null) {
// call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
//Log.e("RESPONSE FROM SERVER", "S: Received Message: '"
// + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
// the socket must be closed. It is not possible to reconnect to
// this socket
// after it is closed, which means a new socket instance has to
// be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
// Declare the interface. The method messageReceived(String message) will
// must be implemented in the MyActivity
// class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
程序执行流水图示