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服务,需要手动重启

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值