2010年1月21日 星期四

Android 簡易msn

Client(Android Activity):

public class AndroidTestMSN extends Activity implements Runnable{
/** Called when the activity is first created. */
public static final String SERVERIP = "xxx.xxx.xxx.xxx";
public static final int SERVERPORT = 13267;
public Button connectButton = null;
public Button sendButton = null;
public EditText inputMessage = null;
public EditText messageContent = null;
private Socket socket;
private BufferedReader br = null;
private String data = null;
private PrintWriter out = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
connectButton = (Button) this.findViewById(R.id.connectBtn);
connectButton.setText("Connect Server");
sendButton = (Button) this.findViewById(R.id.sendBtn);
sendButton.setText("Send message");
inputMessage = (EditText) this.findViewById(R.id.message_input);
inputMessage.setText("edit message");
messageContent = (EditText) this.findViewById(R.id.message_content);
/**
* set the listener of the connectBtn. 1.connect with the server,and set
* the time before this conversation. 2.get the input and out put stream
* of the socket.
*/
connectButton.setOnClickListener(new OnClickListener() {
// messageContent = (EditText) findViewById(R.id.message_content)
public void onClick(View v) {
Log.e("test connectBtn","prepare to connect with the server..");
try {
socket = new Socket(InetAddress.getByName(SERVERIP),SERVERPORT);
//socket = new Socket(SERVERIP, SERVERPORT);
if (socket.isConnected()) {
// Log.e("time", new
// String().valueOf(System.currentTimeMillis()));
messageContent.setText(new Timestamp(System.currentTimeMillis()).toString()
+ "\n");
}
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/**
* set the listener of the sendBtn. 1.get the nick name ,if it is
* null,set is as "android". 2.send the message to the server.
*/
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (out != null) {
String nickName = null;
nickName = "android";
Log.e("test conntetion", "test send data button");
out.println(nickName + ":"
+ inputMessage.getText().toString());
data = new String(nickName + ":"+ inputMessage.getText().toString());
messageHandler.sendEmptyMessage(0);
out.flush();
}
inputMessage.setText("");
}
});
Thread t = new Thread(this);
t.start();
}//onCreate
public void run() {
while (true) {
try {
if (br != null) {
data = new String(br.readLine());
Log.e("get message", data);
messageHandler.sendEmptyMessage(0);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* when messageHandler.sendEmptyMessage(0); runs,the handler will call the
* call back fucntion handleMessage to append the data from the server.
*/
private Handler messageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
messageContent.append(data);
messageContent.append("\n");
}
};
}


Server:

public class myServer {
public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;
public static String s = " ";
public static String inputS = " ";
public static InputStream Is;
public static OutputStream Os;
public static DataInputStream DIS;
public static PrintStream PS;
private static String data = null;
private static BufferedReader br = null;
@SuppressWarnings("deprecation")
public static void main(String args[]) {
ServerSocket server;
Socket socket;


try {
System.out.println("S: Connecting...");
// 在端口4321注冊服務
server = new ServerSocket(SERVERPORT);
socket = server.accept(); // 監聽窗口,等待連接

System.out.println("server ok");
System.out.println("************************************************");
System.out.println("");

// 獲得對應Socket的輸入/輸出流
Is = socket.getInputStream();
Os = socket.getOutputStream();// 建立數據流
DIS = new DataInputStream(Is);
PS = new PrintStream(Os);
DataInputStream in = new DataInputStream(System.in);
Thread receive = new Thread(new Runnable() {
public void run() {
while (true) {
try {
if (DIS != null) {
inputS = DIS.readLine();// 讀入從client傳來的字符串
System.out.println("client said:" + inputS); // 打印字符串
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error1:" + e);
}
}
}// run
});
receive.start();
while (true) {
System.out.println("");
System.out.println("please wait client's message...");
System.out.println("");

// 原本的client input
// inputS = DIS.readLine();// 讀入從client傳來的字符串
// System.out.println("client said:" + inputS); // 打印字符串
// if (inputS.trim().equals("BYE"))
// break; // 如果是"BYE",就退出
System.out.print("you say:");
s = in.readLine(); // 讀取用戶輸入的字符串
PS.println(s); // 將讀取得字符串傳給client
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出
}//while

// 關閉連接
DIS.close(); // 關閉數據輸入流
PS.close(); // 關閉數據輸出流
Is.close(); // 關閉輸入流
Os.close(); // 關閉輸出流
socket.close(); // 關閉sockey
System.out.println("Disconnect");
} catch (Exception e) {
System.out.println("Error2:" + e);
}
}//main
}

layout:




<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/widget31"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <Button android:id="@+id/connectBtn" android:layout_width="147px"
                android:layout_height="42px" android:text="ConnectServer"
                android:layout_x="167px" android:layout_y="2px">
        </Button>
        <EditText android:id="@+id/message_content"
                android:layout_width="315px" android:layout_height="276px"
                android:textSize="18sp" android:layout_x="4px" android:layout_y="41px">
        </EditText>
        <EditText android:id="@+id/message_input"
                android:layout_width="230px" android:layout_height="49px"
                android:text="Message" android:textSize="18sp" android:layout_x="5px"
                android:layout_y="345px">
        </EditText>
        <Button android:id="@+id/sendBtn" android:layout_width="81px"
                android:layout_height="55px" android:text="Send" android:layout_x="238px"
                android:layout_y="345px">
        </Button>
</AbsoluteLayout>



result: