android 简单推送socket长链接
2015-10-26 17:14
323 查看
android socket推送实现
这个代码只供初学者理解推送机制的原理,不建议使用到项目中。因为推送是一个对代码性能以及链接稳定性要求很高的东西。谢谢。服务器端简单创建一个线程循环从ServerSocket中读取消息,并利用PrintWriter将消息推送到每一个设备。扩展可以实现基本的聊天功能。具体实现代码如下:
public Service(Socket socket) { this.socket = socket; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); msg = "user" + this.socket.getInetAddress() + "come toal:" + mList.size(); this.sendmsg(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { // TODO Auto-generated method stub try { while (true) { if ((msg = in.readLine()) != null) { if (msg.equals("exit")) { System.out.println("ssssssss"); mList.remove(socket); in.close(); msg = "user:" + socket.getInetAddress() + "exit total:" + mList.size(); socket.close(); this.sendmsg(); break; } else { msg = socket.getInetAddress() + ":" + msg; this.sendmsg(); } } } } catch (Exception e) { e.printStackTrace(); } } public void sendmsg() { System.out.println(msg); int num = mList.size(); for (int index = 0; index < num; index++) {// /192.168.1.123 // /192.168.1.123 Socket mSocket = mList.get(index); PrintWriter pout = null; try { pout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true); pout.println(msg); } catch (IOException e) { e.printStackTrace(); } } } }
android端利用Socket监听端口来读取消息
public void run() { try { while (true) { if (socket.isConnected()) { if (!socket.isInputShutdown()) { if ((content = in.readLine()) != null) { content += "\n"; mHandler.sendMessage(mHandler.obtainMessage()); } else { } } } } } catch (Exception e) { e.printStackTrace(); }最后上源码
相关文章推荐
- Android动态添加联系人列表
- Android EditText获取焦点事件
- Android里的onTouch事件的分发与消费
- android获取手机电话信息
- android set.list.map简介(小结)
- Android手机重置之后通过file:///mnt/sdcard访问不了本地文件
- EventBus使用详解(二)——EventBus使用进阶
- Android ListView 之 SimpleAdapter 二 (包含 item 中按钮监听)
- Android开发在路上:少去踩坑,多走捷径
- android 坐标之间距离
- EventBus使用详解(一)——初步使用EventBus
- Android控件属性大全(转)
- android 广告轮播小圆点封装
- Android请求返回417解决办法
- android开发环境搭建
- Android 双向滑动菜单完全解析
- Android 解决bug:Android studio 运行、编译项目时导致电脑死机
- 【Android成长之路】最常用和最难用的控件——ListView的浅谈(ListView 的简单用法)
- 美团Android资源混淆保护实践
- android中在代码中设置margin属性