博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 局域网Phone端Socket通信-wifi 聊天应用
阅读量:5121 次
发布时间:2019-06-13

本文共 3876 字,大约阅读时间需要 12 分钟。

到公司第一天,老大说要个Android Native的app。在局域网Wifi下,phone端可以互相发送信息实现聊天。My God,我可从来没有弄过这个啊。没办法,现学呗。

首先想到Socket编程,但是得有Server端。但是手机应用啊。不能在PC再给开个Server吧。所以两个Phone端就互为Client,互为Server端。大方向确定后,先用PC机当server来通信,毕竟网上这方面文章多,继尔建个新的Android App 当Server端,怎么在模拟器中模拟两个手机端口的通信。简单说就是用PC redirect 到emulator端口。.参照我的另一篇文章。

下面的代码为完整的Activity,仅同时支持单个Client。你可以用ExecutorService来实现多个请求。请参照

基本的流程是在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 }

转载于:https://www.cnblogs.com/fengjian/archive/2012/07/05/2578484.html

你可能感兴趣的文章
小程序实战小汇总
查看>>
inner join 与 left join 之间的区别
查看>>
系统对接API调用
查看>>
POJ 3398 Perfect Service(树型动态规划,最小支配集)
查看>>
Servlet的生命周期和工作原理
查看>>
【树链剖分模板】bzoj1036 树的统计
查看>>
一些作业
查看>>
ajax使用异步问题
查看>>
唯有志存高远,方能风行天下
查看>>
Linux产生序列数字
查看>>
【循序渐进学Python】9.异常处理
查看>>
"围观"设计模式(7)--创建型之单例模式(Singleton Pattern)
查看>>
EasyUI基础入门之Pagination(分页)
查看>>
游戏编程入门之测试字体输出
查看>>
poj3889 Fractal Streets 题解报告
查看>>
Linux概述:是个操作系统:CentOS7的安装:先安装minimal
查看>>
神经网络
查看>>
python的第一天
查看>>
POJ 1837 DP
查看>>
【9】log4net 实例
查看>>