究了一下Android推送,方式很多,比如用框架或者用第三方服务,在此并不讨论个中优劣。抱着学习的态度,本人不太喜欢用一些现成的东西,所以自己动手实现了一套简单的推送机制。使用TCP长连接,完成服务器端往客户端推送消息的功能。为了加强服务器端的并发性,使用Java NIO+线程池的模式来实现服务器端的推送服务。
服务器端代码如下:

代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 *
 */
package com.intasect.push;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
 
/**
 * 消息推送服务器
 *
 * @author zengjiantao
 * @date 2013-4-8
 */
public class PushServer extends Thread {
 
        private static final int BUFFER_SIZE = 1024;
 
        /**
         * 服务器连接通道
         */
        private ServerSocketChannel serverSocketChannel;
 
        /**
         * 发送缓冲区
         */
        private final ByteBuffer sendBuf;
 
        /**
         * 端口选择器
         */
        private Selector selector;
 
        /**
         * 服务器端口
         */
        private final int mPort;
 
        /**
         * 线程是否结束的标志
         */
        private final AtomicBoolean shutdown;
 
        /**
         * 发送消息的开关
         */
        private final AtomicBoolean sendable;
 
        /**
         * 发送消息的内容
         */
        private String sendMsg;
 
        private final ExecutorService executorService;
 
        public PushServer(int port) {
                mPort = port;
                // 初始化缓冲区
                sendBuf = ByteBuffer.allocateDirect(BUFFER_SIZE);
                if (selector == null) {
                        // 创建新的Selector
                        try {
                                selector = Selector.open();
                        } catch (final IOException e) {
                                e.printStackTrace();
                        }
                }
 
                startup();
                executorService = Executors.newFixedThreadPool(10);
                shutdown = new AtomicBoolean(false);
                sendable = new AtomicBoolean(false);
        }
 
        private void startup() {
                try {
                        // 打开通道
                        serverSocketChannel = ServerSocketChannel.open();
                        // 绑定到本地端口
                        serverSocketChannel.socket().setSoTimeout(30000);
                        serverSocketChannel.configureBlocking(false);
                        serverSocketChannel.socket().bind(new InetSocketAddress(mPort));
                        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                        System.out.println("服务器端口打开成功");
 
                } catch (final IOException e1) {
                        e1.printStackTrace();
                }
        }
 
        private void select() {
                int nums = 0;
                try {
                        if (selector == null) {
                                return;
                        }
                        nums = selector.select(1000L);
                } catch (final Exception e) {
                        e.printStackTrace();
                }
 
                // 如果select返回大于0,处理事件
                if (nums > 0) {
                        Iterator<SelectionKey> iterator = selector.selectedKeys()
                                        .iterator();
                        while (iterator.hasNext()) {
                                // 得到下一个Key
                                final SelectionKey key = iterator.next();
                                iterator.remove();
                                // 检查其是否还有效
                                if (!key.isValid()) {
                                        continue;
                                }
 
                                // 处理事件
                                if (key.isAcceptable()) {
                                        executorService.execute(new Accepter(key));
                                        // accept(key);
                                } else if (key.isWritable()) {
                                        if (sendable.get()) {
                                                executorService.execute(new Sender(key, sendMsg));
                                        }
                                }
                        }
                        if (sendable.get()) {
                                System.out.println("结束推送消息了");
                        }
                        sendable.set(false);
                }
        }
 
        /**
         * 用于连接的Runnable
         *
         * @author zengjiantao
         * @date 2013-4-11
         */
        class Accepter implements Runnable {
 
                private final SelectionKey key;
 
                public Accepter(SelectionKey key) {
                        this.key = key;
                }
 
                @Override
                public void run() {
                        accept(key);
                }
 
        }
 
        /**
         * 用于发送消息的Runnable
         *
         * @author zengjiantao
         * @date 2013-4-11
         */
        class Sender implements Runnable {
 
                private final SelectionKey key;
 
                private final String msg;
 
                public Sender(SelectionKey key, String msg) {
                        this.key = key;
                        this.msg = msg;
                }
 
                @Override
                public void run() {
                        send(key, msg);
                }
 
        }
 
        /**
         * 接收客户端
         *
         * @param key
         * @throws IOException
         */
        private void accept(SelectionKey key) {
                // 打开通道
                try {
                        SocketChannel socketChannel = ((ServerSocketChannel) key.channel())
                                        .accept();
                        // 绑定到本地端口
                        socketChannel.socket().setSoTimeout(30000);
                        socketChannel.configureBlocking(false);
                        synchronized (selector) {
                                socketChannel.register(selector, SelectionKey.OP_WRITE, this);
                        }
                        System.out.println("端口打开成功");
                } catch (IOException e) {
                        System.out.println("端口打开失败");
                        e.printStackTrace();
                        key.cancel();
                }
        }
 
        @Override
        public void run() {
                // 启动主循环流程
                while (!shutdown.get()) {
                        try {
                                select();
                                try {
                                        Thread.sleep(1000L);
                                } catch (final Exception e) {
                                        e.printStackTrace();
                                }
                        } catch (final Exception e) {
                                e.printStackTrace();
                        }
                }
                shutdown();
        }
 
        /**
         * 打开发送消息的开关
         *
         * @param msg
         */
        private void send(final String msg) {
                sendMsg = msg;
                sendable.set(true);
                System.out.println("开始推送消息了");
        }
 
        /**
         * 向指定连接发送消息
         *
         * @param key
         * @param msg
         */
        private void send(final SelectionKey key, final String msg) {
                try {
                        byte[] out = msg.getBytes();
                        if (out == null || out.length < 1) {
                                return;
                        }
                        synchronized (sendBuf) {
                                sendBuf.clear();
                                sendBuf.put(out);
                                sendBuf.flip();
                        }
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        socketChannel.write(sendBuf);
                } catch (final IOException e) {
                        e.printStackTrace();
                }
        }
 
        /**
         * 断开连接
         */
        public void disConnect() {
                shutdown.set(true);
        }
 
        /**
         * 关闭端口选择器
         */
        private void shutdown() {
                if (serverSocketChannel != null) {
                        try {
                                serverSocketChannel.close();
                                while (serverSocketChannel.isOpen()) {
                                        try {
                                                Thread.sleep(300L);
                                        } catch (final InterruptedException e) {
                                                e.printStackTrace();
                                        }
                                        serverSocketChannel.close();
                                }
                                System.out.println("端口关闭成功");
                        } catch (IOException e1) {
                                System.err.println("端口关闭错误:");
                                e1.printStackTrace();
                        } finally {
                                serverSocketChannel = null;
                        }
                }
                // 关闭端口选择器
                if (selector != null) {
                        try {
                                selector.close();
                                System.out.println("端口选择器关闭成功");
                        } catch (IOException e) {
                                e.printStackTrace();
                        } finally {
                                selector = null;
                        }
                }
        }
 
        public static void main(String[] args) {
                try {
                        final PushServer server = new PushServer(9999);
                        server.start();
                        new Thread(new Runnable() {
 
                                @Override
                                public void run() {
                                        while (true) {
                                                try {
                                                        InputStreamReader input = new InputStreamReader(
                                                                        System.in);
                                                        BufferedReader br = new BufferedReader(input);
                                                        String sendText = br.readLine();
                                                        server.send(sendText);
                                                } catch (IOException e) {
                                                        e.printStackTrace();
                                                }
 
                                        }
                                }
                        }).start();
 
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}

客户端代码如下:

代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*
 *
 */
package com.intasect.push.handle;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicBoolean;
 
import android.os.Handler;
import android.os.Message;
 
import com.intasect.push.utils.Const;
 
/**
 *
 * @author zengjiantao
 * @date 2013-4-8
 */
public class PushClient extends Thread {
 
        private static final int BUFFER_SIZE = 1024;
 
        /**
         * 远程地址
         */
        private final InetSocketAddress mRemoteAddress;
 
        /**
         * 连接通道
         */
        private SocketChannel mSocketChannel;
 
        /**
         * 接收缓冲区
         */
        private final ByteBuffer mReceiveBuf;
 
        /**
         * 端口选择器
         */
        private Selector mSelector;
 
        /**
         * 线程是否结束的标志
         */
        private final AtomicBoolean mShutdown;
         
        /**
         *  消息处理
         */
        private final Handler mHandler;
 
        static {
                java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
                java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");
        }
 
        public PushClient(InetSocketAddress remoteAddress, Handler handler) {
                mRemoteAddress = remoteAddress;
                mHandler = handler;
 
                // 初始化缓冲区
                mReceiveBuf = ByteBuffer.allocateDirect(BUFFER_SIZE);
                if (mSelector == null) {
                        // 创建新的Selector
                        try {
                                mSelector = Selector.open();
                        } catch (final IOException e) {
                                e.printStackTrace();
                        }
                }
                mShutdown = new AtomicBoolean(false);
        }
 
        /**
         * 打开通道
         */
        private void startup() {
                try {
                        // 打开通道
                        mSocketChannel = SocketChannel.open();
                        // 绑定到本地端口
                        mSocketChannel.socket().setSoTimeout(30000);
                        mSocketChannel.configureBlocking(false);
                        if (mSocketChannel.connect(mRemoteAddress)) {
                                System.out.println("开始建立连接:" + mRemoteAddress);
                        }
                        mSocketChannel.register(mSelector, SelectionKey.OP_CONNECT
                                        | SelectionKey.OP_READ, this);
                        System.out.println("端口打开成功");
 
                } catch (final IOException e1) {
                        e1.printStackTrace();
                }
        }
 
        private void select() {
                int nums = 0;
                try {
                        if (mSelector == null) {
                                return;
                        }
                        nums = mSelector.select(1000);
                } catch (final Exception e) {
                        e.printStackTrace();
                }
 
                // 如果select返回大于0,处理事件
                if (nums > 0) {
                        Iterator<SelectionKey> iterator = mSelector.selectedKeys()
                                        .iterator();
                        while (iterator.hasNext()) {
                                // 得到下一个Key
                                final SelectionKey key = iterator.next();
                                iterator.remove();
                                // 检查其是否还有效
                                if (!key.isValid()) {
                                        continue;
                                }
                                // 处理事件
                                try {
                                        if (key.isConnectable()) {
                                                connect();
                                        } else if (key.isReadable()) {
                                                read(key);
                                        }
                                } catch (final Exception e) {
                                        e.printStackTrace();
                                        key.cancel();
                                }
                        }
                }
        }
 
        @Override
        public void run() {
                startup();
                // 启动主循环流程
                while (!mShutdown.get()) {
                        try {
                                // do select
                                select();
                                try {
                                        Thread.sleep(1000);
                                } catch (final Exception e) {
                                        e.printStackTrace();
                                }
                        } catch (final Exception e) {
                                e.printStackTrace();
                        }
                }
                shutdown();
        }
 
        private void connect() throws IOException {
                if (isConnected()) {
                        return;
                }
                // 完成SocketChannel的连接
                mSocketChannel.finishConnect();
                while (!mSocketChannel.isConnected()) {
                        try {
                                Thread.sleep(300);
                        } catch (final InterruptedException e) {
                                e.printStackTrace();
                        }
                        mSocketChannel.finishConnect();
                }
 
        }
 
        public void disConnect() {
                mShutdown.set(true);
        }
 
        private void shutdown() {
                if (isConnected()) {
                        try {
                                mSocketChannel.close();
                                while (mSocketChannel.isOpen()) {
                                        try {
                                                Thread.sleep(300);
                                        } catch (final InterruptedException e) {
                                                e.printStackTrace();
                                        }
                                        mSocketChannel.close();
                                }
                                System.out.println("端口关闭成功");
                        } catch (final IOException e) {
                                System.err.println("端口关闭错误:");
                                e.printStackTrace();
                        } finally {
                                mSocketChannel = null;
                        }
                } else {
                        System.out.println("通道为空或者没有连接");
                }
                // 关闭端口选择器
                if (mSelector != null) {
                        try {
                                mSelector.close();
                                System.out.println("端口选择器关闭成功");
                        } catch (IOException e) {
                                e.printStackTrace();
                        } finally {
                                mSelector = null;
                        }
                }
        }
 
        private void read(SelectionKey key) throws IOException {
                // 接收消息
                final byte[] msg = recieve();
                if (msg != null) {
                        String tmp = new String(msg);
                        System.out.println("返回内容:");
                        System.out.println(tmp);
                        if (mHandler != null) {
                                Message message = mHandler.obtainMessage(Const.PUSH_MSG);
                                message.obj = tmp;
                                mHandler.sendMessage(message);
                        }
                }
        }
 
        private byte[] recieve() throws IOException {
                if (isConnected()) {
                        int len = 0;
                        int readBytes = 0;
 
                        synchronized (mReceiveBuf) {
                                mReceiveBuf.clear();
                                try {
                                        while ((len = mSocketChannel.read(mReceiveBuf)) > 0) {
                                                readBytes += len;
                                        }
                                } finally {
                                        mReceiveBuf.flip();
                                }
                                if (readBytes > 0) {
                                        final byte[] tmp = new byte[readBytes];
                                        mReceiveBuf.get(tmp);
                                        return tmp;
                                } else {
                                        System.out.println("接收到数据为空,重新启动连接");
                                        return null;
                                }
                        }
                } else {
                        System.out.println("端口没有连接");
                }
                return null;
        }
 
        private boolean isConnected() {
                return mSocketChannel != null && mSocketChannel.isConnected();
        }
}

nio加强服务端并发的更多相关文章

  1. Java Se : Java NIO(服务端)与BIO(客户端)通信

    Java目前有三种IO相关的API了,下面简单的说一下: BIO,阻塞IO,最常用的Java IO API,提供一般的流的读写功能.相信学习Java的人,都用过. NIO,非阻塞IO,在JDK1.4中 ...

  2. 关于如何提高Web服务端并发效率的异步编程技术

    最近我研究技术的一个重点是java的多线程开发,在我早期学习java的时候,很多书上把java的多线程开发标榜为简单易用,这个简单易用是以C语言作为参照的,不过我也没有使用过C语言开发过多线程,我只知 ...

  3. 如何提高Web服务端并发效率的异步编程技术

    作为一名web工程师都希望自己做的web应用能被越来越多的人使用,如果我们所做的web应用随着用户的增多而宕机了,那么越来越多的人就会变得越来越少了,为了让我们的web应用能有更多人使用,我们就得提升 ...

  4. 从零讲解搭建一个NIO消息服务端

    本文首发于本博客,如需转载,请申明出处. 假设 假设你已经了解并实现过了一些OIO消息服务端,并对异步消息服务端更有兴趣,那么本文或许能带你更好的入门,并了解JDK部分源码的关系流程,正如题目所说,笔 ...

  5. python并发编程-多线程实现服务端并发-GIL全局解释器锁-验证python多线程是否有用-死锁-递归锁-信号量-Event事件-线程结合队列-03

    目录 结合多线程实现服务端并发(不用socketserver模块) 服务端代码 客户端代码 CIL全局解释器锁****** 可能被问到的两个判断 与普通互斥锁的区别 验证python的多线程是否有用需 ...

  6. 进程池与线程池、协程、协程实现TCP服务端并发、IO模型

    进程池与线程池.协程.协程实现TCP服务端并发.IO模型 一.进程池与线程池 1.线程池 ''' 开进程开线程都需要消耗资源,只不过两者比较的情况下线程消耗的资源比较少 在计算机能够承受范围内最大限度 ...

  7. TCP协议下的服务端并发,GIL全局解释器锁,死锁,信号量,event事件,线程q

    TCP协议下的服务端并发,GIL全局解释器锁,死锁,信号量,event事件,线程q 一.TCP协议下的服务端并发 ''' 将不同的功能尽量拆分成不同的函数,拆分出来的功能可以被多个地方使用 TCP服务 ...

  8. 基于java NIO 的服务端与客户端代码

    在对java NIO  selector 与 Buffer Channel  有一定的了解之后,我们进行编写java nio 实现的 客户端与服务端例子: 服务端: public class NIOC ...

  9. 8.14 day32 TCP服务端并发 GIL解释器锁 python多线程是否有用 死锁与递归锁 信号量event事件线程q

    TCP服务端支持并发 解决方式:开多线程 服务端 基础版 import socket """ 服务端 1.要有固定的IP和PORT 2.24小时不间断提供服务 3.能够支 ...

随机推荐

  1. 【转载】[C#]Log4net中的RollingFileAppender解析

    Log4日志组件的应用确实简单实用,在比较了企业库和Log4的日志功能后,个人觉得Log4的功能更加强大点.补充说明下,我使用的企业库是2.0版本,Log4net是1.2.1版本的. 在Log4net ...

  2. openssl大纲

    1.加密和SSL机制:http://www.cnblogs.com/f-ck-need-u/p/6089523.html 2.openssl命令总指挥:http://www.cnblogs.com/f ...

  3. javascript 零星知识点

    通过js动态生成的元素绑定事件.不能通过js获取元素对象,并赋予事件,最简捷的途径就是将事件直接添加到属性中(DOM0);

  4. Badboy使用数据源Excel进行脚本参数化

    1.首先新建一个Excel,这里示例我写得非常简单,由两由数据组成,第一行为表头.见下图: 2.录制脚本,见上一篇,录制一个非常简单的搜狗查询 3.添加数据源,在Tools面板中找到Data Sour ...

  5. mysql存储过程详细教程

    记录mysql存储过程中的关键语法:DELIMITER //  声明语句结束符,用于区分;CREATE PROCEDURE demo_in_parameter(IN p_in int)  声明存储过程 ...

  6. seaJS循环依赖的解决原理

    seajs模块的六个状态. var STATUS = {  'FETCHING': 1, // The module file is fetching now. 模块正在下载中  'FETCHED': ...

  7. transform初学习

    1.什么是transform? transform主要用于形变,位移和旋转,可用于动画. p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; text-align: jus ...

  8. 将mac上的项目上传到oschina,进行代码托管。

    1.首先看一下自己是否有公钥, 在 我的资料-->SSH公钥  查看,如果没有,添加自己的SSH 公钥: SSH key 可以让你在你的电脑和 Git @ OSC 之间建立安全的加密连接. 2. ...

  9. error-2016-1-18

    SSL 连接出错 错误: "System.Net.Mail.SmtpException"类型的未经处理的异常在 System.dll 中发生 其他信息: SMTP 服务器要求安全连 ...

  10. Android Studio使用百度地图示例BaiduMapsApiASDemo

    Android Studio使用百度地图示例BaiduMapsApiASDemo 用自己AVD下的debug.keystore替换掉项目中的debug.keystore 生成自己的签名 同样的方法生成 ...