首页 > 其他分享 >Springboot websocket 的简单使用

Springboot websocket 的简单使用

时间:2023-02-03 14:36:11浏览次数:44  
标签:websocket Springboot System Override session 简单 println public out

项目结构:094548_gafp_3477913.png

引入依赖:

"org.springframework.boot:spring-boot-starter-websocket",
"org.springframework.boot:spring-boot-starter-thymeleaf",

启动类:

public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

 

消息处理类:

@Service
public class MyHandler extends TextWebSocketHandler {
 
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("成功建立连接");
        session.sendMessage(new TextMessage("成功建立socket连接"));
        session.sendMessage(new TextMessage("发送一波消息"));
        System.out.println("关闭。。。。。。。。。。。");
        session.close(); // 发送完就关闭
        System.out.println("关闭成功");
    }
 
    // 处理客户端发来的信息
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        System.out.println("0000" + message.getPayload());
        WebSocketMessage message1 = new TextMessage("server:" + message);
        try {
            session.sendMessage(message1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        System.out.println("连接出错");
    }
 
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接已关闭:" + status);
    }
 
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

 

拦截器:

public class WebSocketInterceptor implements HandshakeInterceptor {
 
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Map<String, Object> map) throws Exception {
        System.out.println("----------------WTF------------------");
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            HttpSession session = serverHttpRequest.getServletRequest().getSession();
            String sid = serverHttpRequest.getServletRequest().getParameter("sid");
            System.out.println("连接参数:sid----->" + sid);
            if (session != null) {
                map.put("userId", 4); // 设置参数给session
            }
 
        }
        return true;
    }
 
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("========什么鬼=========");
    }
}

 

页面配置

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/mytest").setViewName("/mytest");
    }
}

 

Websocket配置

@Configuration
@EnableWebSocket
public class MyWebSocketConfig implements WebSocketConfigurer {
 
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/myHandler").addInterceptors(new WebSocketInterceptor());
    }
 
    @Bean
    public WebSocketHandler myHandler() {
        return new MyHandler();
    }
 
}

 

mytest.html:

<!DOCTYPE html>
 
<html xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8"/>
<head>
    <title>Home</title>
    <script th:src="@{sockjs.min.js}"></script>
    <script th:src="@{stomp.min.js}"></script>
    <script th:src="@{jquery.js}"></script>
</head>
<body>
 
<script type="text/javascript">
    function connect() {
        var ws = new WebSocket("ws://localhost:8090/myHandler?sid=1")
        ws.onopen = function () {
            console.log("onpen");
            ws.send("{}");
            ws.send("哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈");
        }
        ws.onclose = function () {
            console.log("===========================================");
            console.log("onclose");
        }
 
        ws.onmessage = function (msg) {
            console.log("发消息来了!");
            var item = $("#response");
            var msg1 = item.html();
            item.html(msg1 + " <br/> " + msg.data);
            console.log(msg.data);
        }
    }
</script>
 
<div>
    <button id="connect" onclick="connect();">开始打印</button>
</div>
 
<div id="conversationDiv">
    <p id="response"></p>
</div>
 
</body>
</html>

 

application.properties改了一下端口:

server.port=8090

 

转载于:https://my.oschina.net/u/3477913/blog/1510212

标签:websocket,Springboot,System,Override,session,简单,println,public,out
From: https://www.cnblogs.com/zhang1f/p/17089166.html

相关文章

  • 剑指offer——Day21 位运算(简单)
    Day212023.2.3位运算(简单)剑指offer15.二进制中1的个数自己实现这个题最简单的做法很容易理解,就是执行while(n!=0)循环,然后在循环中n>>=1,并判断如果n&1==1那么就要对......
  • MySQL数据库的安装(安装以及简单数据库操作)
    有关mysql数据库 MySQL是目前比较流行的关系型数据库管理系统之一,其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,深受中小型网站用户的欢迎。安装方式一​​点击......
  • Linux 配置Tomcat、SpringBoot项目开机自启
    Linux配置Tomcat、SpringBoot项目开机自启#javaenvironment指定java环境exportJAVA_HOME=/home/jdk1.8.0_11exportCLASSPATH=.:${JAVA_HOME}/jre/lib/rt.jar:${JAV......
  • springboot连接rabbitmq报错:Failed to check/redeclare auto-delete queue(s).
    问题springboot项目使用​​spring-boot-starter-amqp​​连接rabbitmq时出现报错:Failedtocheck/redeclareauto-deletequeue(s).思路这类问题是因为没有连接上rabbitmq......
  • SpringBoot发送虚拟请求~
    1、创建一个测试用的TestController@RestControllerpublicclassTestController{@GetMapping("/test")publicStringtest(){System.out.println(......
  • Spring Boot + WebSocket 实时监控异常
    本文已经收录到Github仓库,该仓库包含计算机基础、Java基础、多线程、JVM、数据库、Redis、Spring、Mybatis、SpringMVC、SpringBoot、分布式、微服务、设计模式、架构、校......
  • springboot(一)
    基础1.介绍与入门1.1介绍SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程。Spring程序缺点依赖设置繁琐以前写S......
  • 防止数据重复提交的6种方法(超简单)!
    有位朋友,某天突然问磊哥:在Java中,防止重复提交最简单的方案是什么?这句话中包含了两个关键信息,第一:防止重复提交;第二:最简单。于是磊哥问他,是单机环境还是分布式环境?得到......
  • SpringBoot的静态路径映射处理
    springboot的默认静态路径:resources下面的/static;/public;/resources;/META-INF/resources这四个文件路径静态路径的默认映射路径是:/**;意思就是说浏览器......
  • SpringBoot默认的8080端口在哪?
    配置文件中,点击port 进入到ServerProperties类 ServerProperties这个类中,读取配置文件server开头的配置 定位类文件所在位置 找到对应jar包的META-INF下的......