public class MainActivity extends Activity {
private Button button;
private EditText edit_name;
private TextView tv_info;
private Socket client;
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
//接受传过来的数据
String name=(String) msg.obj;
tv_info.setText(client.getInetAddress().toString()+"
"+name);
//或者
// tv_info.append(name);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 寻找控件
findView();
// 接受服务端发送的信息
acceptInfo();
// 按钮点击监听事件
setOnclick();
}
private void acceptInfo() {
// 由于读取服务端的信息是耗时操作,所以必须创建新的线程
new Thread() {
public void run() {
// 创建socket对象
try {
client = new Socket("169.254.103.7", 9999);
// 循环读取数据
BufferedReader br = new BufferedReader(
new InputStreamReader(client.getInputStream(),
"gbk"));
while(true)
{
String data = br.readLine();
//将读取的数据发送给主线程
handler.sendMessage(handler.obtainMessage(1, data));
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
private void setOnclick() {
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 获取输入的信息
String str = edit_name.getText().toString();
/*//设置输入框的数据
edit_name.setText("");*/
//将数据传给服务器
try {
PrintWriter pw=new PrintWriter(client.getOutputStream());
pw.println(str);
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void findView() {
button = (Button) findViewById(R.id.button);
edit_name = (EditText) findViewById(R.id.edit_name);
tv_info = (TextView) findViewById(R.id.tv_info);
}
}