一、简介
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。
二、相关代码
服务器端:
消息实体
package com.test.socket; public class ChatObject { private String userName; private String message; public ChatObject() { } public ChatObject(String userName, String message) { super(); this.userName = userName; this.message = message; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
监听器
package com.test.socket; import com.corundumstudio.socketio.AckRequest; import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOServer; import com.corundumstudio.socketio.listener.DataListener; public class CharteventListener implements DataListener<ChatObject> { SocketIOServer server; public void setServer(SocketIOServer server) { this.server = server; } public void onData(SocketIOClient client, ChatObject data, AckRequest ackSender) throws Exception { //chatevent为 事件的名称,data为发送的内容 this.server.getBroadcastOperations().sendEvent("chatevent", data); } }
服务器端启动代码
package com.test.socket; import com.corundumstudio.socketio.Configuration; import com.corundumstudio.socketio.SocketIOServer; public class SocketServer { public static void main(String[] args) throws InterruptedException { Configuration config = new Configuration(); config.setHostname("localhost"); config.setPort(9092); SocketIOServer server = new SocketIOServer(config); CharteventListener listner = new CharteventListener(); listner.setServer(server); // chatevent为事件名称 server.addEventListener("chatevent", ChatObject.class, listner); // 启动服务 server.start(); Thread.sleep(Integer.MAX_VALUE); server.stop(); } }
运行该类,服务器端即可启动
客户端message.html代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script src="./jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript" src="./socket.io/socket.io.js"></script> <style> body { padding:20px; } #console { height: 400px; overflow: auto; } .username-msg {color:orange;} .connect-msg {color:green;} .disconnect-msg {color:red;} .send-msg {color:#888} </style> </head> <body> <h1>Netty-socketio示例</h1> <br/> <div id="console" class="well"> </div> <form class="well form-inline" onsubmit="return false;"> <input id="name" class="input-xlarge" type="text" placeholder="用户名称..."/> <input id="msg" class="input-xlarge" type="text" placeholder="发送内容..."/> <button type="button" onClick="sendMessage()" class="btn">Send</button> <button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button> </form> </body> <script type="text/javascript"> var socket = io.connect('http://localhost:9092'); socket.on('connect', function() { output('<span class="connect-msg">Client has connected to the server!</span>'); }); socket.on('chatevent', function(data) { output('<span class="username-msg">' + data.userName + ':</span> ' + data.message); }); socket.on('disconnect', function() { output('<span class="disconnect-msg">The client has disconnected!</span>'); }); function sendDisconnect() { socket.disconnect(); } function sendMessage() { var userName = $("#name").val() var message = $('#msg').val(); $('#msg').val(''); socket.emit('chatevent', {userName: userName, message: message}); } function output(message) { var currentTime = "<span class='time'>" + new Date() + "</span>"; var element = $("<div>" + currentTime + " " + message + "</div>"); $('#console').prepend(element); } </script> </html>
客户端需要引入jquery与socket.io.js文件。
在浏览器打开该html文件,输入用户名称以及消息内容发送,服务器端获取到发送的内容之后,会将该消息发送会客户端,客户端接收到从服务器端返回的消息或,将该消息添加到页面并显示。运行效果如下图: