WebSocket消息推送

websocket握手过程(建立连接的过程)

使用网页端尝试和服务器建立websocket连接。 网页端会先给服务器发起—个HTTP请求,这个HTTP请求中会带有特殊的header。
Connection: Upgrade
Upgrade: Websocket
这两个header其实就是在告知服务器,我们要进行协议升级。 如果服务器支持websocket,就会返回一个特殊的HTTP响应,这个响应的状态码是101(切换协议)。 客户端和服务器之间就开始使用websocket来进行通信了。

websocket代码实例

 后端

1.引入依赖WebSocket
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.继承父类TextWebSocketHandler,重写API代码
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

//将该类注入到spring
@Component
public class WebsocketTest extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接建立成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //message.getPayload得到数据载荷
        System.out.println("收到的消息:" + message.getPayload());

        //服务器将消息返回给客户端
        session.sendMessage(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭");
    }
}
3.注册

将websocketTest进行注册与路径"/websocket"进行关联,最上面加入@EnableWebSocket注解,开启WebSocket服务。

import com.example.gobang.TestDemo.WebsocketTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import javax.annotation.Resource;

@Configuration
@EnableWebSocket//开启WebSocket
public class RegWebSocket implements WebSocketConfigurer {

    @Resource
    private WebsocketTest websocketTest;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        //将WebsocketTest类进行注册与路径"/websocket"进行关联
        registry.addHandler(websocketTest,"/websocket");
    }
}

前端

<input type="text"  id="msg">
    <button id="submit">提交</button>
    <script>
        //创建websocket实例
        let webScoket = new WebSocket("ws://127.0.0.1:8080/websocket");

        webScoket.onopen = function(){
            console.log("连接建立");
        }

        webScoket.onmessage = function(e){
            console.log("收到消息:" + e.data);
        }

        webScoket.onerror = function(){
            console.log("连接异常");
        }

        webScoket.onclose = function(){
            console.log("连接关闭");
        }


        //点击按钮。通过websocket发送请求

        let msg = document.querySelector("#msg");
        let webBtn = document.querySelector("#submit");
        webBtn.onclick = function(){
            console.log("发送消息:" + msg.value);
            webScoket.send(msg.value);
        }
    </script>

4.结果

 当点击提交时,客户端将“你好WebSocket”发给服务器,服务器handleTextMessage函数会收到message消息,然后将消息再推送给客户端,客户端触发实例WebSocket的onmessage函数从而接收服务器发送的消息

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值