netty-socketio+spring boot 长链接 实时通信 消息推送

**

Springboot 集成 netty-socketio, 基于 Netty 实现, 进行 Sockcet 长连接,进行实时通讯,消息推送。

**

1、maven 配置

    	<dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.49.Final</version>
        </dependency>
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.18</version>
        </dependency>

2、NettyServer

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author hua
 */
@Component
@Slf4j
public class NettyServer {
    public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();

    /**
     * 客户端连接的时候触发
     * @param client
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String mac = client.getHandshakeData().getSingleUrlParam("mac");
        //存储SocketIOClient,用于发送消息
        socketIOClientMap.put(mac, client);
        //回发消息
        log.info("客户端:" + client.getSessionId() + "已连接,mac=" + mac);
    }

    /**
     * 客户端事件
     * @param data    客户端发送数据
     */
    @OnEvent(value = "messageevent") //messageevent与客户端事件名称一致
    public void onEvent( String data) {
        log.info("发来消息:" + data);
        //回发消息
        for (SocketIOClient client : socketIOClientMap.values()) {
            if (client.isChannelOpen()) {
                client.sendEvent("messageevent", data); //发送消息、
                client.sendEvent("Broadcast", "当前时间", System.currentTimeMillis());//广播消息
            }
        }
    }
}

3、启动类配置

@Slf4j
@SpringBootApplication 
public class Application implements CommandLineRunner {
    @Autowired
    private SocketIOServer socketIOServer;

    public static void main(String[] args) {
        SpringApplication.run(XiaoyuAdminApplication.class, args);
        log.info("application start success startTime:{}", DateUtil.getDateTime());
    }

    /**
     * Callback used to run the bean.
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        socketIOServer.start();
    }

    /**
     * netty-socketio服务器
     */
    @Bean
    public SocketIOServer socketIOServer() {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setHostname("0.0.0.0");  
        config.setPort(9092);
        SocketConfig socketConfig = config.getSocketConfig();
        if(!socketConfig.isReuseAddress()){
            socketConfig.setReuseAddress(true);
            log.info("是否绑定了:{}", socketConfig.isReuseAddress());
        }
        return new SocketIOServer(config);
    }

    /**
     * 用于扫描netty-socketio的注解,比如 @OnConnect、@OnEvent
     */
    @Bean
    public SpringAnnotationScanner springAnnotationScanner() {
        return new SpringAnnotationScanner(socketIOServer());
    }
}

4、前端

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>websocket-java-socketio</title>
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
</head>
<body>
</body>
 
<script type="text/javascript">
	 var test = window.location.host;
	  //  192.168.0.101:8183
	  var host;
	  if(test.indexOf(":") != -1){
	    var arr = test.split(':');
	    host = arr[0]
	  }else{
	    host = test
	  }
    var socket = io.connect(host+":9092?mac="++ Math.random());
 
    //监听服务器连接事件
    socket.on('connect', function(){ 
    	socket.emit('simple', "hello server");
    });
    //监听服务器关闭服务事件
    socket.on('disconnect', function(){ 
    	
    });
    
    //监听服务器端发送消息事件 messageevent 要与后台声明的事件名称一致
    socket.on('messageevent', function(data) {
		console.log("服务器发送的消息是:", data);
    });
</script>
</html>


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
netty-websocket-spring-boot-starter是一个基于Netty实现的WebSocket框架,可以方便地在Spring Boot应用中集成WebSocket功能。使用该框架可以快速构建实时通信消息推送等功能。 下面是一个使用netty-websocket-spring-boot-starter的简单案例: 1. 在pom.xml中添加依赖: ```xml <dependency> <groupId>com.github.wujiuye</groupId> <artifactId>netty-websocket-spring-boot-starter</artifactId> <version>1.0.0.RELEASE</version> </dependency> ``` 2. 编写WebSocket处理器 ```java @ServerEndpoint("/websocket/{userId}") @Component public class WebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); private Session session; private String userId; @OnOpen public void onOpen(Session session, @PathParam("userId") String userId) { this.session = session; this.userId = userId; logger.info("WebSocket连接建立,userId: {}", userId); } @OnMessage public void onMessage(String message) { logger.info("收到来自客户端的消息:{}", message); sendMessage("服务端已收到消息:" + message); } @OnClose public void onClose() { logger.info("WebSocket连接关闭,userId: {}", userId); } @OnError public void onError(Throwable t) { logger.error("WebSocket连接异常,userId: {}", userId, t); } public void sendMessage(String message) { try { this.session.getBasicRemote().sendText(message); } catch (IOException e) { logger.error("发送WebSocket消息失败,userId: {}", userId, e); } } } ``` 3. 配置WebSocket 在配置类中添加@EnableWebSocket注解,启用WebSocket功能,同时,也可以配置WebSocket的一些参数,例如端口号、路径等。 ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/websocket/{userId}") .setAllowedOrigins("*"); } } ``` 4. 测试WebSocket 使用浏览器或WebSocket客户端连接WebSocket服务端,例如:ws://localhost:8080/websocket/123,其中123为userId。 以上就是一个简单的netty-websocket-spring-boot-starter使用案例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值