1

【笔记】WebSocket学习笔记

 1 year ago
source link: https://loli.fj.cn/2023/01/09/WebSocket%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

WebSocket学习笔记

WebSocket协议请求头和响应头

  • 将请求从HTTP协议升级到WebSocket协议
GET ws://localhost HTTP/1.1
Host: localhost
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Key: xxxxxxxxxxxxxxxxxxxxxx==
Sec-WebSocket-Extensions: permessage-deflate
Sec-WebSocket-Version: 13

101:101响应码表示升级协议成功

HTTP/1.1 101 Seitching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: xxxxxxxxxxxxxxxxxxxxxx==
Sec-WebSocket-Extensions: permessage-deflate

创建WebSocket对象

<url>:ws协议的服务端地址(以ws://开头)

const ws = new WebSocket(<url>);

发送数据给服务端

ws.send();

WebSocket对象的事件

连接建立时

ws.open = function() {}

接收到数据时

  • 客户端接收服务端发送的数据时
ws.message = function() {}

发生错误时

ws.error = function() {}

连接关闭时

ws.close = function() {}
  • 定义一个POJO类
  • 通过@OnMessage标注的方法处理接收消息
  • 通过session对象中的getBasicRemote()方法发送消息

@ServerEndpoint("/"):指定请求的资源路径

src/main/java/pojo/MsgEndPoint.java

@ServerEndpoint("/")
public class MsgEndPoint {

private Session session

// 客户端接收服务端消息时执行
@OnMessage
public void onMessage(String message, Session session) throws IOException {
// 接收消息
System.out.println(message);
// 发送消息
session.getBasicRemote().sendText("");
}

// 会话创建时执行
@OnOpen
public void onOpen(Session session) {
this.session = session;
}

// 会话结束时执行
@OnClose
public void onClose(Session session) {

}

// 会话报错时执行
@OnError
public void onError(Session session, Throwalbe error) {

}

}

SpringBoot项目整合WebSocket

pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

哔哩哔哩——黑马程序员西安中心


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK