• Spring Boot集成Socket


    使用WebSocket模块

    • 导入spring-boot-starter-websocket依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    
    • 编写WebSocket配置类
    package cn.java2016.demo.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    @Configuration
    public class WebSocketConfiguration {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
        	return new ServerEndpointExporter();
        }
    }
    
    • 配置WebSocket处理类
    package cn.java2016.demo.component;
    
    import java.io.IOException;
    
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    
    import org.springframework.stereotype.Component;
    
    @ServerEndpoint("/websocket")   // 访问路径: ws://localhost:8080/websocket
    @Component
    public class WebSocketServer {
    
        // 第一次连接调用
        @OnOpen
        public void open(Session session) throws IOException {
        	System.out.println("connect..");
        	session.getBasicRemote().sendText("server: 登陆成功!");
        }
        
        // 关闭连接调用
        @OnClose
        public void close() {
        	System.out.println("disconnect..");
        }
        
        // 接收消息
        @OnMessage
        public void message(String message, Session session) {
        	System.out.println("client send: " + message);
        }
    }
    
    • 前端页面代码
    // 判断浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        var socket = new WebSocket("ws://localhost:8080/websocket")
        // 第一次连接
        socket.onopen = function (ev) {
            console.log(ev)
            // 向服务器发送消息
            socket.send('sfsd')
        }
        // 连接被关闭: 浏览器刷新 | 浏览器关闭 | 服务器关闭
        socket.onclose = function (ev) {
            console.log(ev)
        }
        // 连接错误
        socket.onerror = function (ev) {
            console.log(ev)
        }
        // 接收消息
        socket.onmessage = function (ev) {
            // 打印消息
            console.log(ev.data)
        }
    }
    

    使用SocketIO模块

    • 引入SocketIO依赖
    <dependency>
        <groupId>com.corundumstudio.socketio</groupId>
        <artifactId>netty-socketio</artifactId>
        <version>1.7.16</version>
    </dependency>
    
    • 加入SocketIO配置类
    package cn.java2016.demo.config;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import com.corundumstudio.socketio.SocketIOServer;
    import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
    
    @Configuration
    public class SocketIOConfiguration implements CommandLineRunner{
        
        @Bean
        public SocketIOServer socketIOServer() {
        	com.corundumstudio.socketio.Configuration conf = new com.corundumstudio.socketio.Configuration();
        	// 设置ip地址和端口
        	conf.setHostname("localhost");
        	conf.setPort(8081); 
        	return new SocketIOServer(conf);
        }
        
        @Bean
        public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketIOServer) {
        	return new SpringAnnotationScanner(socketIOServer);
        }
        
        @Override
        public void run(String... args) throws Exception {
            // 启动socket服务
        	socketIOServer().start();
        }
    }
    
    • 配置SocketIO服务组件
    package cn.java2016.demo.component;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import com.corundumstudio.socketio.SocketIOClient;
    import com.corundumstudio.socketio.SocketIOServer;
    import com.corundumstudio.socketio.annotation.OnConnect;
    import com.corundumstudio.socketio.annotation.OnDisconnect;
    import com.corundumstudio.socketio.annotation.OnEvent;
    
    import cn.java2016.demo.pojo.User;
    
    /**
     * WebSocket服务不会热加载,需要手动重启
     * @author Administrator
     */
    @Component
    public class SocketServer {
    	
        @Autowired
        public SocketIOServer socketServer;
        
        // 连接打开
        @OnConnect
        public void connect(SocketIOClient client) {
        	System.out.println("socketio connect..");
        	client.sendEvent("data", "连接成功!");
        //		socketServer.getClient(client.getSessionId()).sendEvent("data", "sdfsdf");
        //		System.out.println(client.getSessionId());
        }
        
        // 连接关闭
        @OnDisconnect
        public void disconnect(SocketIOClient client) {
        	System.out.println("socketio disconnect..");
        }
        
        // 监听login事件
        @OnEvent("login")
        public void login(SocketIOClient client, String name) {
        	System.out.println("login.." + name);
        //		socketServer.getClient(uuid)socketClient.sendEvent("data", new User(name, age));
        	client.sendEvent("data", "login success2..");
        }
        
        // 监听register事件, 自动注入pojo类,用法和SpringMvc基本一致
        @OnEvent("register")
        public void register(User user, SocketIOClient client) {
        	System.out.println("register..");
        	System.out.println(user);
        	// 发送消息
        	client.sendEvent("data", new User(user.getName(), user.getAge()).toString());
        //		socketServer.getClient(client.getSessionId()).sendEvent("data", new User(user.getName(), user.getAge()));
        }
    }
    
    • 前台代码,引入socketio依赖
    <script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.dev.js"></script>
    
    var socket = io("ws://localhost:8081")
    // 监听连接事件
    socket.on('connect', function () {
        console.log('connection..')
    })
    // 关闭连接
    socket.on('disconnect', function () {
        console.log('connection close..')
    })
    // 监听data事件
    socket.on('data', function (data) {
        console.log(data)
    })
    // 触发事件,并传递json数据,在后台会自动被注入成User对象
    socket.emit("register", {name: "张三", age: 18})
    socket.emit('login')
    

    注:Spring Boot DevTools热加载不会重启socket服务,需要手动重启

  • 相关阅读:
    mysql初始化/usr/local/mysql/bin/mysqld: error while loading shared libraries: libnuma.so.1: cannot open shared object file: No such file or directory
    centos重启出现type Control-D to continue【fsck使用】
    find 常用命令
    保持简单----纪念丹尼斯•里奇(Dennis Ritchie)
    最有效的五个方法,彻底控制你的负面情绪,你有吗
    ERROR 1366 (HY000): Incorrect string value: 'xE9x83x91xE5xB7x9E' for column 'aa' at row 1 MySQL 字符集
    Got fatal error 1236 from master when reading data from binary log: 'Could not find first log file name in binary log index file'
    mysql从5.6升级到5.7后出现 Expression #1 of ORDER BY clause is not in SELECT list,this is incompatible with DISTINCT
    mysqld_safe error: log-error set to '/data/log/mysqld.log', however file don't exists. Create writable for user 'mysql'.The server quit without updating PID file (/data/mysql/mysqld.pid)
    ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
  • 原文地址:https://www.cnblogs.com/dagger9527/p/11836667.html
Copyright © 2020-2023  润新知