当前位置:   article > 正文

基于Netty实现的netty-socketio实现WebSocket

如何将netty项目改为socketio

介绍

netty-socketio是socket.io使用Java语言基于Netty网络库编写的WebSocket库.功能非常强大,简单易用,稳定可靠.

  1. <dependency>
  2. <groupId>com.corundumstudio.socketio</groupId>
  3. <artifactId>netty-socketio</artifactId>
  4. <version>1.7.14</version>
  5. </dependency>

后端使用Demo

1.配置SocketIOServer

  1. @Value("${my.server.host}")
  2. private String host;
  3. @Value("${my.server.port}")
  4. private Integer port;
  5. @Bean
  6. public SocketIOServer socketIOServer() {
  7. Configuration config = new Configuration();
  8. config.setOrigin(null); // 注意如果开放跨域设置,需要设置为null而不是"*"
  9. config.setPort(this.port);
  10. config.setSocketConfig(new SocketConfig());
  11. config.setWorkerThreads(100);
  12. config.setAuthorizationListener(handshakeData -> true);
  13. final SocketIOServer server = new SocketIOServer(config);
  14. server.start();
  15. return server;
  16. }
  17. @Bean
  18. public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketIOServer){
  19. return new SpringAnnotationScanner(socketIOServer);
  20. }

2.连接,断开连接,推送消息,接收消息

  1. @OnConnect
  2. public void onConnect(SocketIOClient client) {
  3. String no0 = client.getHandshakeData().getSingleUrlParam("no");
  4. logger.info("工号为no = {}的用户建立WebSocket连接", no0);
  5. int no = 0;
  6. try {
  7. no = Integer.parseInt(no0);
  8. } catch (Exception e) {
  9. logger.error("建立WebSocket连接,获取工号信息异常");
  10. }
  11. if (no != 0) {
  12. noClientMap.put(no, client);
  13. }
  14. }
  15. @OnDisconnect
  16. public void onDisConnect(SocketIOClient client) {
  17. String no0 = client.getHandshakeData().getSingleUrlParam("no");
  18. logger.info("工号为no = {}的用户断开WebSocket连接", no0);
  19. int no = 0;
  20. try {
  21. no = Integer.parseInt(no0);
  22. } catch (Exception e) {
  23. logger.error("建立WebSocket连接,获取工号信息异常");
  24. }
  25. if (no != 0) {
  26. noClientMap.remove(no, client);
  27. }
  28. }
  29. @OnEvent(value = "noEvent")
  30. public void onEvent(SocketIOClient client, Integer data, AckRequest request) {
  31. logger.info("工号no = {}的用户推送消息", data );
  32. if (data != null && data > 0) {
  33. noClientMap.put(data, client);
  34. }
  35. }
  36. @Override
  37. public void toOne(int no, String eventName, Object data) {
  38. SocketIOClient socketIOClient = noClientMap.get(no);
  39. if (socketIOClient != null) {
  40. try {
  41. // 推送消息即为调用SocketIOClient的sendEvent方法
  42. socketIOClient.sendEvent(eventName, data);
  43. } catch (Exception e) {
  44. logger.info("推送消息给工号为no = {}的用户异常", no, e.getMessage());
  45. }
  46. }
  47. }
  48. @Override
  49. public void toAll(Object data) {
  50. for (Integer no : noClientMap.keySet()) {
  51. toOne(no, NettyEventEnum.RUNNING_TASK.getName(), data);
  52. }
  53. }

前端Demo代码

1.引入socket.io文件

<script src="https://cdn.bootcss.com/socket.io/2.1.0/socket.io.js"></script>

2.建立连接、断开连接、接收消息、推送消息

  1. <script >
  2. var username = 'username';
  3. var socket = io.connect('http://localhost:12350?no=' + username);
  4. socket.on('connect', function () {
  5. console.log('连接')
  6. });
  7. socket.on('runningTask', function (data) {
  8. console.log("收到全服数据")
  9. console.log(data);
  10. });
  11. socket.on('taskResult', function (data) {
  12. console.log("收到个人数据")
  13. console.log(data);
  14. });
  15. // 可以是任意类型的数据,这里用了一个json对象,后端有对应的实体类
  16. var jsonObject = {
  17. "username": "username1",
  18. "to": 2
  19. };
  20. socket.emit('messageevent', jsonObject);
  21. socket.on('disconnect', function () {
  22. console.log("断开")
  23. });
  24. </script>

 

转载于:https://my.oschina.net/hutaishi/blog/1820047

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/83534
推荐阅读
相关标签
  

闽ICP备14008679号