mengmweng

导航

nio加强服务端并发

究了一下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();
        }
}

posted on 2013-12-07 14:43  mengmweng  阅读(296)  评论(0编辑  收藏  举报