您的位置:首页 > 移动开发 > Android开发

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();
}
最后上源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: