基于netty-socketio的web推送服务

释放双眼,带上耳机,听听看~!

在WEB项目中,服务器向WEB页面推送消息是一种常见的业务需求。PC端的推送技术可以使用socket建立一个长连接来实现。传统的web服务都是客户端发出请求,服务端给出响应。但是现在直观的要求是允许特定时间内在没有客户端发起请求的情况下服务端主动推送消息到客户端。最近的预警系统中,需要服务端向预警系统推送商品行情和K线相关的数据,所以对常用的WEB端推送方式进行调研。常见的手段主要包括以下几种:

  • 轮询(俗称“拉”,polling):Ajax 隔一段时间向服务器发送请求,询问数据是否发生改变,从而进行增量式的更新。轮询的时间间隔成了一个问题:间隔太短,会有大量的请求发送到服务器,会对服务器负载造成影响;间隔太长业务数据的实时性得不到保证。连。使用轮询的优点是实现逻辑简单,缺点是无效请求的数量多,在用户量较大的情况下,服务器负载较高。因此轮询的方式通常在并发数量较少、并且对消息实时性要求不高的情况下使用。
  • 长轮询技术(long-polling):客户端向服务器发送Ajax请求,服务器接到请求后hold住连接,直到有新消息或超时(设置)才返回响应信息并关闭连接,客户端处理完响应信息后再向服务器发送新的请求。长轮询技术的优点是消息实时性高,无消息的情况下不会进行频繁的请求;缺点是服务端维持和客户端的连接会消耗掉一部分资源。
  • 插件提供socket方式:比如利用Flash XMLSocket,Java Applet套接口,Activex包装的socket。

优点是对原生socket的支持,和PC端和移动端的实现方式相似;缺点是浏览器需要安装相应的插件。

  • WebSocket:是HTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术。其

优点是更好的节省服务器资源和带宽并达到实时通讯;
缺点是目前还未普及,浏览器支持不好;

综上,考虑到浏览器兼容性和性能问题,采用长轮询(long-polling)是一种比较好的方式。
netty-socketio是一个开源的Socket.io服务器端的一个java的实现, 它基于Netty框架。 项目地址为: https://github.com/mrniko/netty-socketio

以下基于Netty-socketIO实现一个简单的聊天室功能,首先引入依赖:


1
2
3
4
5
6
1<dependency>
2        <groupId>com.corundumstudio.socketio</groupId>
3   <artifactId>netty-socketio</artifactId>
4   <version>1.7.3</version>
5</dependency>
6

定义Listen,用户监听Oncennect、disconnect和OnMSG事件:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
1@Service("eventListenner")
2public class EventListenner {
3    @Resource(name = "clientCache")
4    private SocketIOClientCache clientCache;
5
6    @Resource(name = "socketIOResponse")
7    private SocketIOResponse socketIOResponse;
8    
9    @OnConnect
10    public void onConnect(SocketIOClient client) {
11       System.out.println("建立连接");
12    }
13
14    @OnEvent("OnMSG")
15    public void onSync(SocketIOClient client, MsgBean bean) {
16        System.out.printf("收到消息-from: %s to:%s\n", bean.getFrom(), bean.getTo());
17        clientCache.addClient(client, bean);
18        SocketIOClient ioClients = clientCache.getClient(bean.getTo());
19        System.out.println("clientCache");
20        if (ioClients == null) {
21            System.out.println("你发送消息的用户不在线");
22            return;
23        }
24        socketIOResponse.sendEvent(ioClients,bean);
25    }
26
27    @OnDisconnect
28    public void onDisconnect(SocketIOClient client) {
29        System.out.println("关闭连接");
30    }
31}
32
33

定义消息发送类:


1
2
3
4
5
6
7
8
9
1@Service("socketIOResponse")
2public class SocketIOResponse {
3    public void sendEvent(SocketIOClient client, MsgBean bean) {
4        System.out.println("推送消息");
5        client.sendEvent("OnMSG", bean);
6    }
7}
8
9

定义Cache用于保存所有和Web端的连接:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1@Service("clientCache")
2public class SocketIOClientCache {
3    //String:EventType类型
4    private Map<String,SocketIOClient> clients=new ConcurrentHashMap<String,SocketIOClient>();
5
6    //用户发送消息添加
7    public void addClient(SocketIOClient client,MsgBean msgBean){
8        clients.put(msgBean.getFrom(),client);
9    }
10
11    //用户退出时移除
12    public void remove(MsgBean msgBean) {
13        clients.remove(msgBean.getFrom());
14    }
15    
16    //获取所有
17    public  SocketIOClient getClient(String to) {
18        return clients.get(to);
19    }
20}
21
22

定义Server:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1//继承InitializingBean,使Spring加载完配置文件,自动运行如下方法
2@Service("chatServer")
3public class ChatServer implements InitializingBean{
4    @Resource
5    private EventListenner eventListenner;
6    public void afterPropertiesSet() throws Exception {
7        Configuration config = new Configuration();
8        config.setPort(9098);
9        
10        SocketConfig socketConfig = new SocketConfig();
11        socketConfig.setReuseAddress(true);
12        socketConfig.setTcpNoDelay(true);
13        socketConfig.setSoLinger(0);
14        config.setSocketConfig(socketConfig);
15        config.setHostname("localhost");
16        
17        SocketIOServer server = new SocketIOServer(config);
18        server.addListeners(eventListenner);
19        server.start();
20        System.out.println("启动正常");
21    }
22}
23
24

定义MSGbean:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1public class MsgBean {  
2    private String from;
3    private String to;
4    private String content;
5    
6    public String getFrom() {
7        return from;
8    }
9    public void setFrom(String from) {
10        this.from = from;
11    }
12    public String getTo() {
13        return to;
14    }
15    public void setTo(String to) {
16        this.to = to;
17    }
18    public String getContent() {
19        return content;
20    }
21    public void setContent(String content) {
22        this.content = content;
23    }
24    
25    @Override
26    public String toString() {
27        return "MsgBean [from=" + from + ", to=" + to + ", content=" + content + "]";
28    }
29}
30
31

定义Main:


1
2
3
4
5
6
7
8
9
1public class Main {
2    public static void main(String[] args) {
3        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/applicationContext-push.xml");
4        context.start();
5        context.getBean("chatServer");
6    }
7}
8
9

HTML页面:


1
2
3
4
5
6
7
8
9
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
1<!DOCTYPE html>
2<html>
3<head>
4<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
5<title>Socketio chat</title>
6<script src="./jquery-1.7.2.min.js" type="text/javascript"></script>
7<script type="text/javascript" src="./socket.io.js"></script>
8<style>
9body {
10    padding: 20px;
11}
12#console {
13    height: 400px;
14    overflow: auto;
15}
16.username-msg {
17    color: orange;
18}
19.connect-msg {
20    color: green;
21}
22.disconnect-msg {
23    color: red;
24}
25.send-msg {
26    color: #888
27}
28</style>
29</head>
30<body>
31    <h1>Netty-socketio chat demo</h1>
32    <br />
33    <div id="console" class="well"></div>
34    <form class="well form-inline" οnsubmit="return false;">
35      <input id="from" class="input-xlarge" type="text" placeholder="from. . . " />
36        <input id="to" class="input-xlarge" type="text" placeholder="to. . . " />
37        <input id="content" class="input-xlarge" type="text" placeholder="content. . . " />
38        <button type="button" onClick="sendMessage()" class="btn">Send</button>
39        <button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button>
40    </form>
41</body>
42<script type="text/javascript">
43    var socket = io.connect('http://localhost:9098');
44    socket.on('connect',function() {
45        output('<span class="connect-msg">Client has connected to the server!</span>');
46    });
47    
48    socket.on('OnMSG', function(data) {
49        output('<span class="username-msg">' + data.content + ' : </span>');
50    });
51    
52    socket.on('disconnect',function() {
53        output('<span class="disconnect-msg">The client has disconnected! </span>');
54    });
55    
56    function sendDisconnect() {
57        socket.disconnect();
58    }
59    
60    function sendMessage() {
61        var from = $("#from").val();
62      var to = $("#to").val();
63        var content = $('#content').val();
64        socket.emit('OnMSG', {
65            from : from,
66            to : to,
67          content : content
68        });
69    }
70    
71    function output(message) {
72        var currentTime = "<span class='time' >" + new Date() + "</span>";
73        var element = $("<div>" + currentTime + " " + message + "</div>");
74        $('#console').prepend(element);
75    }
76</script>
77</html>
78

给TA打赏
共{{data.count}}人
人已打赏
安全技术

详解Node.js API系列 Crypto加密模块(2) Hmac

2021-12-21 16:36:11

安全技术

从零搭建自己的SpringBoot后台框架(二十三)

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索