MyClient
package com.baidu.day11_myclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private BufferedReader br;
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String str = (String) msg.obj;
textView.setText(textView.getText().toString() + "/t/n" + str);
// textView.append(str);
};
};
private TextView textView;
private PrintWriter pw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
textView = (TextView) findViewById(R.id.message);
final EditText editText = (EditText) findViewById(R.id.say);
Button button = (Button) findViewById(R.id.button1);
try {
// 建立和服务器链接
Socket client = new Socket("169.254.109.73", 9999);
br = new BufferedReader(new InputStreamReader(
client.getInputStream()));
pw = new PrintWriter(client.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 启动一个线程,随时接收服务端信息
new Thread() {
public void run() {
// 使用while循环
while (true) {
// 读取当前服务器的一句话,读到为止,如读不到会继续向下走
try {
String str = br.readLine();
// 把str显示到textview
handler.sendMessage(handler.obtainMessage(1, str));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
button.setOnClickListener(new OnClickListener() {
private String sayData;
public void onClick(View v) {
sayData = editText.getText().toString();
// 创建线程
new Thread() {
public void run() {
pw.println(sayData);
pw.flush();
};
}.start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}