spring集成webSocket实现服务端向前端推送消息

该博客详细介绍了如何使用Spring集成WebSocket实现服务端向前端的实时消息推送。包括前端建立WebSocket连接的代码,Spring项目中引入相关依赖,服务端WebSocket配置及连接代码,Controller层定义发送消息的方法,以及Service层调用WebSocket发送消息的流程。通过这些步骤,最终成功实现了WebSocket的测试连接和消息发送。
摘要由CSDN通过智能技术生成

1、前端连接websocket代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>


    <head lang="en">
        <meta charset="UTF-8">
        <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
        <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
        <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
        <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <title>webSocket-用户66</title>
        <script type="text/javascript">
            $(function() {
                var websocket;
                if('WebSocket' in window) {
                                        console.log("此浏览器支持websocket");
                    websocket = new WebSocket("ws://localhost:8080/residential/websocketDemo/66");
                } else if('MozWebSocket' in window) {
                    alert("此浏览器只支持MozWebSocket");
                } else {
                    alert("此浏览器只支持SockJS");
                }
                websocket.onopen = function(evnt) {
                 console.log(evnt);
                    $("#tou").html("链接服务器成功!")
                };
                websocket.onmessage = function(evnt) {
                    $("#msg").html($("#msg").html() + "<br/>" + evnt.data);
                };
                websocket.onerror = function(evnt) {};
                websocket.onclose = function(evnt) {
               		console.log("与服务器断开了链接!");
                    $("#tou").html("与服务器断开了链接!")
                }
                
                $('#close').bind('click', function() {
                	websocket.close();
                });
                
                $('#send').bind('click', function() {
                    send();
  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值