SpringBoot集成netty-socket.io

netty-socekt.IO官網(wǎng)

socket.io是一個(gè)netty.socket node版的java實(shí)現(xiàn)版,其性能優(yōu)于webSocket等socket技術(shù),socket.io有nameSpace等,分區(qū)方式,比較靈活。

服務(wù)端實(shí)現(xiàn)

maven

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

prop

originHost為socket客戶端的地址,serverHost請(qǐng)使用ip,lz在使用過程中嘗試過使用localhost,但服務(wù)未能調(diào)用成功。

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

socketConfig

socketIoConfig用于生產(chǎn)bean,在socketService等其他地方調(diào)用該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啟動(dòng)項(xiàng)目的時(shí)候,啟動(dòng)socket服務(wù)

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事件,當(dāng)客戶端發(fā)起連接時(shí)調(diào)用,本文中將clientid與sessionid存入數(shù)據(jù)庫(kù)
     * //方便后面發(fā)送消息時(shí)查找到對(duì)應(yīng)的目標(biāo)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 + " 設(shè)備建立連接");
    }

    /**
     * 添加@OnDisconnect事件,客戶端斷開連接時(shí)調(diào)用,刷新客戶端信息
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String uuid = client.getSessionId().toString();
        clientsMap.remove(uuid);
        LOGGER.debug("IP: " + client.getRemoteAddress().toString() + " UUID: " + uuid + " 設(shè)備斷開連接");
    }

    /**
     * 給所有連接客戶端推送消息
     *
     * @param eventType 推送的事件類型
     * @param message   推送的內(nèi)容
     */
    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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容