基于echo的ws实现

This commit is contained in:
lingling 2023-04-21 20:28:23 +08:00
parent 02b57be779
commit 20cc0d355f
4 changed files with 71 additions and 35 deletions

1
go.mod
View File

@ -4,6 +4,7 @@ go 1.16
require ( require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/gorilla/websocket v1.5.0
github.com/howeyc/fsnotify v0.9.0 // indirect github.com/howeyc/fsnotify v0.9.0 // indirect
github.com/idoubi/goutils v1.3.2 // indirect github.com/idoubi/goutils v1.3.2 // indirect
github.com/idoubi/goz v1.4.4 // indirect github.com/idoubi/goz v1.4.4 // indirect

2
go.sum
View File

@ -13,6 +13,8 @@ github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keL
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/howeyc/fsnotify v0.9.0 h1:0gtV5JmOKH4A8SsFxG2BczSeXWWPvcMT0euZt5gDAxY= github.com/howeyc/fsnotify v0.9.0 h1:0gtV5JmOKH4A8SsFxG2BczSeXWWPvcMT0euZt5gDAxY=
github.com/howeyc/fsnotify v0.9.0/go.mod h1:41HzSPxBGeFRQKEEwgh49TRw/nKBsYZ2cF1OzPjSJsA= github.com/howeyc/fsnotify v0.9.0/go.mod h1:41HzSPxBGeFRQKEEwgh49TRw/nKBsYZ2cF1OzPjSJsA=
github.com/idoubi/goutils v1.1.0/go.mod h1:BVikG2hf3aDWXsBzBw3X7l4jSuuxNQQVgrxQ6amIAOk= github.com/idoubi/goutils v1.1.0/go.mod h1:BVikG2hf3aDWXsBzBw3X7l4jSuuxNQQVgrxQ6amIAOk=

64
main.go
View File

@ -3,53 +3,47 @@ package main
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"strconv"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware" "github.com/labstack/echo/v4/middleware"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
) )
type result struct { func ws(c echo.Context) error {
// 通过json标签指定json字段名 websocket.Handler(server).ServeHTTP(c.Response(), c.Request())
Sataus int `json:"sataus"` return nil
Code int `json:"code"` }
Tip_number int `json:"tip_number"` func add(c echo.Context) error {
tip_number++
return c.String(http.StatusOK, strconv.Itoa(tip_number))
}
func server(ws *websocket.Conn) {
defer ws.Close()
fmt.Printf("new connection\n")
for {
if tip_number == 0 {
continue
}
var strr string = strconv.Itoa(tip_number)
err := websocket.Message.Send(ws, strr)
if err != nil {
fmt.Print(err)
}
tip_number = 0
}
} }
var tip_number int = 0 var tip_number int = 0
func main() { func main() {
e := echo.New() e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{AllowOrigins: []string{"*"}, AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE}})) e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.GET("/add", add) e.Static("/", "./public")
e.GET("/ws", ws) e.GET("/ws", ws)
e.GET("/add", add)
e.Logger.Fatal(e.Start(":1323")) e.Logger.Fatal(e.Start(":1323"))
} }
func add(c echo.Context) error {
tip_number++
return c.JSON(http.StatusOK, "ok")
}
func ws(c echo.Context) error {
websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
for {
// Write
err := websocket.Message.Send(ws, tip_number)
if err != nil {
c.Logger().Error(err)
}
// Read
msg := ""
err = websocket.Message.Receive(ws, &msg)
if err != nil {
c.Logger().Error(err)
}
fmt.Printf("%s\n", msg)
}
}).ServeHTTP(c.Response(), c.Request())
return nil
}

39
public/index.html Normal file
View File

@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebSocket</title>
</head>
<body>
<p id="output"></p>
<script>
var loc = window.location;
var uri = 'ws:';
if (loc.protocol === 'https:') {
uri = 'wss:';
}
uri += '//' + loc.host;
uri += loc.pathname + 'ws';
ws = new WebSocket(uri)
ws.onopen = function() {
console.log('Connected')
}
ws.onmessage = function(evt) {
var out = document.getElementById('output');
out.innerHTML += evt.data + '<br>';
}
// setInterval(function() {
// ws.send('Hello, Server!');
// }, 1000);
</script>
</body>
</html>