WebSocket

Using net WebSocket

Server

server.go

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

Using gorilla WebSocket

Server

server.go

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

Client

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>

Output

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!

Source Code

Maintainers