COOKBOOK(手册) - WebSocket

优质
小牛编辑
136浏览
2023-12-01

WebSocket

使用 net 库的 WebSocket

服务端

server.go

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/labstack/echo"
  6. "github.com/labstack/echo/middleware"
  7. "golang.org/x/net/websocket"
  8. )
  9. func hello(c echo.Context) error {
  10. websocket.Handler(func(ws *websocket.Conn) {
  11. defer ws.Close()
  12. for {
  13. // Write
  14. err := websocket.Message.Send(ws, "Hello, Client!")
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. // Read
  19. msg := ""
  20. err = websocket.Message.Receive(ws, &msg)
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. fmt.Printf("%s\n", msg)
  25. }
  26. }).ServeHTTP(c.Response(), c.Request())
  27. return nil
  28. }
  29. func main() {
  30. e := echo.New()
  31. e.Use(middleware.Logger())
  32. e.Use(middleware.Recover())
  33. e.Static("/", "../public")
  34. e.GET("/ws", hello)
  35. e.Logger.Fatal(e.Start(":1323"))
  36. }

使用 gorilla 的 WebSocket

服务端

server.go

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/labstack/echo"
  6. "github.com/gorilla/websocket"
  7. "github.com/labstack/echo/middleware"
  8. )
  9. var (
  10. upgrader = websocket.Upgrader{}
  11. )
  12. func hello(c echo.Context) error {
  13. ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
  14. if err != nil {
  15. return err
  16. }
  17. defer ws.Close()
  18. for {
  19. // Write
  20. err := ws.WriteMessage(websocket.TextMessage, []byte("Hello, Client!"))
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. // Read
  25. _, msg, err := ws.ReadMessage()
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. fmt.Printf("%s\n", msg)
  30. }
  31. }
  32. func main() {
  33. e := echo.New()
  34. e.Use(middleware.Logger())
  35. e.Use(middleware.Recover())
  36. e.Static("/", "../public")
  37. e.GET("/ws", hello)
  38. e.Logger.Fatal(e.Start(":1323"))
  39. }

客户端

index.html

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>WebSocket</title>
  6. </head>
  7. <body>
  8. <p id="output"></p>
  9. <script>
  10. var loc = window.location;
  11. var uri = 'ws:';
  12. if (loc.protocol === 'https:') {
  13. uri = 'wss:';
  14. }
  15. uri += '//' + loc.host;
  16. uri += loc.pathname + 'ws';
  17. ws = new WebSocket(uri)
  18. ws.onopen = function() {
  19. console.log('Connected')
  20. }
  21. ws.onmessage = function(evt) {
  22. var out = document.getElementById('output');
  23. out.innerHTML += evt.data + '<br>';
  24. }
  25. setInterval(function() {
  26. ws.send('Hello, Server!');
  27. }, 1000);
  28. </script>
  29. </body>
  30. </html>

输出示例

Client

  1. Hello, Client!
  2. Hello, Client!
  3. Hello, Client!
  4. Hello, Client!
  5. Hello, Client!

Server

  1. Hello, Server!
  2. Hello, Server!
  3. Hello, Server!
  4. Hello, Server!
  5. Hello, Server!