到公司第一天,老大说要个Android Native的app。在局域网Wifi下,phone端可以互相发送信息实现聊天。My God,我可从来没有弄过这个啊。没办法,现学呗。
首先想到Socket编程,但是得有Server端。但是手机应用啊。不能在PC再给开个Server吧。所以两个Phone端就互为Client,互为Server端。大方向确定后,先用PC机当server来通信,毕竟网上这方面文章多,继尔建个新的Android App 当Server端,怎么在模拟器中模拟两个手机端口的通信。简单说就是用PC redirect 到emulator端口。.参照我的另一篇文章。http://www.cnblogs.com/fengjian/archive/2012/07/05/2578519.html
下面的代码为完整的Activity,仅同时支持单个Client。你可以用ExecutorService来实现多个请求。请参照http://www.blogjava.net/sterning/archive/2007/10/15/152940.html
基本的流程是在Create的时候,就开启Server Thread服务来监听Client。当点击send的时候来请求建立Socket连接。
在真正环境下测试过,注意路由器的防火墙设置。
1 public class ChatActivity extends Activity { 2 3 private TextView tv_ip = null; 4 private TextView tv_showmes = null; 5 private EditText ed_msg = null; 6 private Button btn_send = null; 7 private static final int PORT = 8192; 8 private static final int SERVERPORT = 8192; // listen port 9 10 /** Called when the activity is first created. */ 11 12 @Override 13 public void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_chat); 16 // init client; 17 tv_ip = (TextView) findViewById(R.id.et_ip); 18 tv_showmes = (TextView) findViewById(R.id.tv_mes_show); 19 ed_msg = (EditText) findViewById(R.id.et_mes); 20 // btn_login = (Button) findViewById(R.id.Button01); 21 btn_send = (Button) findViewById(R.id.btn_send); 22 23 new Thread(new Service()).start(); 24 25 btn_send.setOnClickListener(new Button.OnClickListener() { 26 public void onClick(View v) { 27 try { 28 String chathost = tv_ip.getText().toString().trim(); 29 Socket socket = new Socket(chathost, PORT); 30 BufferedReader in = new BufferedReader( 31 new InputStreamReader(socket.getInputStream())); 32 PrintWriter out = new PrintWriter(new BufferedWriter( 33 new OutputStreamWriter(socket.getOutputStream())), 34 true); 35 String msg = ed_msg.getText().toString()+"\n"; 36 if (socket.isConnected()) { 37 if (!socket.isOutputShutdown()) { 38 out.write(msg); 39 out.flush(); 40 } 41 } 42 } catch (IOException ex) { 43 ShowDialog("The IP address can't access!"); 44 } 45 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 46 long[] pattern = {100, 50, 100, 50, 100, 50, 100, 50}; // OFF/ON/OFF/ON... 47 vibrator.vibrate(pattern, -1); 48 } 49 }); 50 51 } 52 53 54 public Handler mHandler = new Handler() { 55 @Override 56 public void handleMessage(Message msg) { 57 super.handleMessage(msg); 58 Bundle b = msg.getData(); 59 String mesg = b.getString("mes"); 60 tv_showmes.setText(tv_showmes.getText().toString() + mesg+"\n"); 61 } 62 }; 63 64 public void ShowDialog(String msg) { 65 new AlertDialog.Builder(this).setTitle("notification").setMessage(msg) 66 .setPositiveButton("ok", new DialogInterface.OnClickListener() { 67 68 public void onClick(DialogInterface dialog, int which) { 69 // TODO Auto-generated method stub 70 71 } 72 }).show(); 73 } 74 75 @Override 76 public boolean onCreateOptionsMenu(Menu menu) { 77 getMenuInflater().inflate(R.menu.activity_chat, menu); 78 return true; 79 } 80 81 class Service implements Runnable { 82 private Socket socket; 83 private BufferedReader in = null; 84 private String msg = ""; 85 private ServerSocket server = null; 86 87 public void run() { 88 Looper.prepare(); 89 try { 90 server = new ServerSocket(SERVERPORT); 91 } catch (IOException e1) { 92 // TODO Auto-generated catch block 93 e1.printStackTrace(); 94 } 95 while(true){ 96 try { 97 socket = server.accept(); 98 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 99 msg = "user" +this.socket.getInetAddress().toString() + ":" 100 +in.readLine(); 101 102 //notice the UI thread to refactor the ui 103 Message message = new Message(); 104 Bundle b = new Bundle(); 105 b.putString("mes", msg); 106 message.setData(b); 107 ChatActivity.this.mHandler.sendMessage(message); 108 109 } catch (IOException e) { 110 e.printStackTrace(); 111 } 112 } 113 } 114 } 115 116 117 }