You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/en/docs/hertz/tutorials/third-party/protocol/websocket.md
+104-3Lines changed: 104 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,9 +1,9 @@
1
1
---
2
2
title: "Websocket"
3
-
date: 2022-09-13
3
+
date: 2025-12-12
4
4
weight: 4
5
5
keywords: ["WebSocket", "HTTP", "hijack", "TCP"]
6
-
description: "Hertz implements support for WebSocket based on hijack."
6
+
description: "Hertz implements support for Gorilla WebSocket based on hijack."
7
7
---
8
8
9
9
WebSocket is a type of full-duplex communication that can be performed on a single TCP connection and is located at the application layer of the OSI model.
@@ -13,7 +13,108 @@ In the WebSocket API, the browser and the server only need to complete a handsha
13
13
Hertz provides support for WebSocket and adapts it in Hertz by referring to [gorilla/websocket](https://github.com/gorilla/websocket) using `hijack`.
14
14
The usage and parameters are basically the same.
15
15
16
-
## Install
16
+
> **⚠️ Deprecated**
17
+
>
18
+
> The `hertz-contrib/websocket` middleware is now deprecated.
19
+
> Hertz recommends all users to migrate to the official `gorilla/websocket` toolchain using the [Hertz HTTP Adaptor](../../basic-feature/http-adaptor/).
20
+
>
21
+
> See the migration guide below.
22
+
23
+
## Migration Guide
24
+
25
+
1. Remove deprecated dependencies
26
+
27
+
```sh
28
+
github.com/hertz-contrib/websocket
29
+
```
30
+
31
+
2. Use hertz adaptor
32
+
33
+
```go
34
+
// Before (using hertz-contrib/websocket)
35
+
import"github.com/hertz-contrib/websocket"
36
+
varupgrader = websocket.HertzUpgrader{}
37
+
funcecho(_context.Context, c *app.RequestContext) {
The following example demonstrates how to modify the `server.go` code in the hertz-contrib/echo [example](https://github.com/hertz-contrib/websocket/tree/main/examples/echo) to directly use the adaptor with gorilla/websocket. There is no change to `client.go`
58
+
59
+
```go
60
+
package main
61
+
62
+
import (
63
+
"flag"
64
+
"html/template"
65
+
"log"
66
+
"net/http"
67
+
68
+
"github.com/cloudwego/hertz/pkg/app/server"
69
+
"github.com/cloudwego/hertz/pkg/common/adaptor"
70
+
"github.com/gorilla/websocket"
71
+
)
72
+
73
+
varaddr = flag.String("addr", "localhost:8080", "http service address")
74
+
75
+
varupgrader = websocket.Upgrader{} // use default options
WebSocket 是一种可以在单个 TCP 连接上进行全双工通信,位于 OSI 模型的应用层。WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就可以创建持久性的连接,并进行双向数据传输。
0 commit comments