美文网首页
SpringBoot集成netty-socket.io

SpringBoot集成netty-socket.io

作者: nickbi | 来源:发表于2018-07-11 01:10 被阅读0次

    netty-socekt.IO官网

    socket.io是一个netty.socket node版的java实现版,其性能优于webSocket等socket技术,socket.io有nameSpace等,分区方式,比较灵活。

    服务端实现

    maven

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

    prop

    originHost为socket客户端的地址,serverHost请使用ip,lz在使用过程中尝试过使用localhost,但服务未能调用成功。

    #socketIO
    wss.server.port=9093
    wss.server.host=0.0.0.0
    wss.origin.host=http://localhost:8080
    

    socketConfig

    socketIoConfig用于生产bean,在socketService等其他地方调用该SocketIOServer的bean

    import com.corundumstudio.socketio.SocketIOServer;
    import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author nickBi
     * create on 2018/7/5.
     */
    @Configuration
    public class SocketIoConfig {
        @Value("${wss.server.host}")
        private String host;
    
        @Value("${wss.server.port}")
        private Integer port;
    
        @Value("${wss.origin.host}")
        private String originHost;
    
    
        @Bean
        public SocketIOServer socketIOServer() {
            com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
            config.setHostname(host);
            config.setPort(port);
            config.setOrigin(originHost);
            final SocketIOServer server = new SocketIOServer(config);
            return server;
        }
    
        @Bean
        public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
            return new SpringAnnotationScanner(socketServer);
        }
    }
    

    socketRunner,在springboot启动项目的时候,启动socket服务

    import com.corundumstudio.socketio.SocketIOServer;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    /**
     * @author nickBi
     * create on 2018/7/5.
     */
    @Component
    public class SocketRunner implements CommandLineRunner {
    
        @Autowired
        private SocketIOServer server;
    
        @Override
        public void run(String... args) throws Exception {
            server.start();
        }
    }
    

    SocketService

    mport com.corundumstudio.socketio.SocketIOClient;
    import com.corundumstudio.socketio.SocketIOServer;
    import com.corundumstudio.socketio.annotation.OnConnect;
    import com.corundumstudio.socketio.annotation.OnDisconnect;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @author nickBi
     * create on 2018/7/5.
     */
    @Service
    public class SocketService {
        private static final Logger LOGGER = LoggerFactory.getLogger(SocketService.class);
    
        @Autowired
        private SocketIOServer server;
    
        private static Map<String, SocketIOClient> clientsMap = new HashMap<String, SocketIOClient>();
    
        /**
         * 添加connect事件,当客户端发起连接时调用,本文中将clientid与sessionid存入数据库
         * //方便后面发送消息时查找到对应的目标client,
         *
         * @param client
         */
        @OnConnect
        public void onConnect(SocketIOClient client) {
            String uuid = client.getSessionId().toString();
            clientsMap.put(uuid, client);
            LOGGER.debug("IP: " + client.getRemoteAddress().toString() + " UUID: " + uuid + " 设备建立连接");
        }
    
        /**
         * 添加@OnDisconnect事件,客户端断开连接时调用,刷新客户端信息
         */
        @OnDisconnect
        public void onDisconnect(SocketIOClient client) {
            String uuid = client.getSessionId().toString();
            clientsMap.remove(uuid);
            LOGGER.debug("IP: " + client.getRemoteAddress().toString() + " UUID: " + uuid + " 设备断开连接");
        }
    
        /**
         * 给所有连接客户端推送消息
         *
         * @param eventType 推送的事件类型
         * @param message   推送的内容
         */
        public void sendMessageToAllClient(String eventType, String message) {
            Collection<SocketIOClient> clients = server.getAllClients();
            for (SocketIOClient client : clients) {
                client.sendEvent(eventType, message);
            }
        }
    
    
    }
    

    客户端

    <!DOCTYPE html>
    <html>
    <head>
    
            <title>Demo Chat</title>
    
            <link href="bootstrap.css" rel="stylesheet">
    
        <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>
    
    
        <script src="js/socket.io/socket.io.js"></script>
            <script src="js/moment.min.js"></script>
            <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    
        <script>
    
                    var userName1 = 'user1_' + Math.floor((Math.random()*1000)+1);
            var chat1Socket =  io.connect('http://localhost:9092');
                    function connectHandler(parentId) {
                return function() {
                                output('<span class="connect-msg">Client has connected to the server!</span>', parentId);
                            }
                    }
    
                    function messageHandler(parentId) {
                            return function(data) {
                     output('<span class="username-msg">' + data.userName + ':</span> ' + data.message, parentId);
                    }
                    }
    
                    function disconnectHandler(parentId) {
                            return function() {
                     output('<span class="disconnect-msg">The client has disconnected!</span>', parentId);
                            }
                    }
    
            function sendMessageHandler(parentId, userName, chatSocket) {
                            var message = $(parentId + ' .msg').val();
                            $(parentId + ' .msg').val('');
    
                            var jsonObject = {'@class': 'com.corundumstudio.socketio.demo.ChatObject',
                                              userName: userName,
                                              message: message};
                            chatSocket.json.send(jsonObject);
            }
    
    
            chat1Socket.on('connect', connectHandler('#chat1'));
    
            chat1Socket.on('message', messageHandler('#chat1'));
    
            chat1Socket.on('disconnect', disconnectHandler('#chat1'));
    
                    function sendDisconnect1() {
                            chat1Socket.disconnect();
                    }
    
               
            function sendMessage1() {
                            sendMessageHandler('#chat1', userName1, chat1Socket);
            }
    
            function output(message, parentId) {
                            var currentTime = "<span class='time'>" +  moment().format('HH:mm:ss.SSS') + "</span>";
                            var element = $("<div>" + currentTime + " " + message + "</div>");
                $(parentId + ' .console').prepend(element);
            }
    
            $(document).keydown(function(e){
                if(e.keyCode == 13) {
                    $('#send').click();
                }
            });
        </script>
    </head>
    
    <body>
    
        <h1>Namespaces demo chat</h1>
    
        <br/>
    
            <div id="chat1" style="width: 49%; float: left;">
                <h4>chat1</h4>
                <div class="console well">
                </div>
                <form class="well form-inline" onsubmit="return false;">
                   <input class="msg input-xlarge" type="text" placeholder="Type something..."/>
                   <button type="button" onClick="sendMessage1()" class="btn" id="send">Send</button>
                   <button type="button" onClick="sendDisconnect1()" class="btn">Disconnect</button>
                </form>
            </div>
         </body>
    
    </html>
    
    

    相关文章

      网友评论

          本文标题:SpringBoot集成netty-socket.io

          本文链接:https://www.haomeiwen.com/subject/mgdcpftx.html