netty-socketio

一、简介

  netty-socketio是一个开源的Socket.io服务器端的一个java的实现,它基于Netty框架。项目地址为:https://github.com/mrniko/netty-socketio 。socket.io是一个跨浏览器使用websocket为实时实时应用提供服务。本例子使用maven构建,依赖如下:

<dependency>
    <groupId>com.corundumstudio.socketio</groupId>
    <artifactId>netty-socketio</artifactId>
    <version>1.6.5</version>
</dependency>

  客户端使用的是socket.io-client,下载地址为:https://github.com/Automattic/socket.io-client

二、相关代码

  服务器端:

  消息实体

 1 package com.test.socket;
 2 
 3 public class ChatObject {
 4 
 5     private String userName;
 6     private String message;
 7 
 8     public ChatObject() {
 9     }
10 
11     public ChatObject(String userName, String message) {
12         super();
13         this.userName = userName;
14         this.message = message;
15     }
16 
17     public String getUserName() {
18         return userName;
19     }
20 
21     public void setUserName(String userName) {
22         this.userName = userName;
23     }
24 
25     public String getMessage() {
26         return message;
27     }
28 
29     public void setMessage(String message) {
30         this.message = message;
31     }
32 
33 }

  监听器

 1 package com.test.socket;
 2 
 3 import com.corundumstudio.socketio.AckRequest;
 4 import com.corundumstudio.socketio.SocketIOClient;
 5 import com.corundumstudio.socketio.SocketIOServer;
 6 import com.corundumstudio.socketio.listener.DataListener;
 7 
 8 public class CharteventListener implements DataListener<ChatObject> {
 9 
10     SocketIOServer server;
11 
12     public void setServer(SocketIOServer server) {
13         this.server = server;
14     }
15     
16     public void onData(SocketIOClient client, ChatObject data,
17             AckRequest ackSender) throws Exception {
18         //chatevent为 事件的名称,data为发送的内容
19         this.server.getBroadcastOperations().sendEvent("chatevent", data);
20     }
21 
22 }

  服务器端启动代码

 1 package com.test.socket;
 2 
 3 import com.corundumstudio.socketio.Configuration;
 4 import com.corundumstudio.socketio.SocketIOServer;
 5 
 6 public class SocketServer {
 7     public static void main(String[] args) throws InterruptedException {
 8 
 9         Configuration config = new Configuration();
10         config.setHostname("localhost");
11         config.setPort(9092);
12 
13         SocketIOServer server = new SocketIOServer(config); 
14 
15         CharteventListener listner = new CharteventListener();
16         listner.setServer(server);
17         //   chatevent为事件名称
18         server.addEventListener("chatevent", ChatObject.class, listner); 
19         //启动服务
20         server.start();
21 
22         Thread.sleep(Integer.MAX_VALUE);
23 
24         server.stop();
25     }
26 
27 }
28                                                 

  运行该类,服务器端即可启动

  客户端message.html代码如下:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5 <title>Insert title here</title>
 6 <script src="./jquery-1.9.1.js" type="text/javascript"></script>
 7 <script type="text/javascript" src="./socket.io/socket.io.js"></script>
 8     <style>
 9         body { 
10             padding:20px;
11         }
12         #console { 
13             height: 400px; 
14             overflow: auto; 
15         }
16         .username-msg {color:orange;}
17         .connect-msg {color:green;}
18         .disconnect-msg {color:red;}
19         .send-msg {color:#888}
20     </style>
21 </head>
22 <body>
23     <h1>Netty-socketio示例</h1>
24     <br/>
25     <div id="console" class="well">
26     </div>
27         <form class="well form-inline" onsubmit="return false;">
28            <input id="name" class="input-xlarge" type="text" placeholder="用户名称..."/>
29            <input id="msg" class="input-xlarge" type="text" placeholder="发送内容..."/>
30            <button type="button" onClick="sendMessage()" class="btn">Send</button>
31            <button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button>
32         </form>
33 </body>
34 <script type="text/javascript">
35         var socket =  io.connect(http://localhost:9092);
36 
37         socket.on(connect, function() {
38             output(<span class="connect-msg">Client has connected to the server!</span>);
39         });
40         
41         socket.on(chatevent, function(data) {
42             output(<span class="username-msg"> + data.userName + :</span>  + data.message);
43         });
44         
45         socket.on(disconnect, function() {
46             output(<span class="disconnect-msg">The client has disconnected!</span>);
47         });
48         function sendDisconnect() {
49             socket.disconnect();
50         }
51         
52         function sendMessage() {
53             var userName = $("#name").val()
54             var message = $(#msg).val();
55             $(#msg).val(‘‘);
56             socket.emit(chatevent, {userName: userName, message: message});
57         }
58         
59         function output(message) {
60             var currentTime = "<span class=‘time‘>" +  new Date() + "</span>";
61             var element = $("<div>" + currentTime + " " + message + "</div>");
62             $(#console).prepend(element);
63         }
64     </script>
65 </html>

  客户端需要引入jquery与socket.io.js文件。

  在浏览器打开该html文件,输入用户名称以及消息内容发送,服务器端获取到发送的内容之后,会将该消息发送会客户端,客户端接收到从服务器端返回的消息或,将该消息添加到页面并显示。运行效果如下图:

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。