Scott

websocket 2 years ago

go
websocket
1262个字符
共有174人围观

golang服务端demo

package main

import (
  "fmt"
  "golang.org/x/net/websocket"
  "net/http"
)

type Server struct {
  conns map[*websocket.Conn]bool
}

func NewServer() *Server {
  return &Server{
    conns: make(map[*websocket.Conn]bool),
  }
}

func (s *Server) handleWS(ws *websocket.Conn) {
  fmt.Println("new incoming connection from client:", ws.RemoteAddr())
  s.conns[ws] = true
  s.readLoop(ws)
}

func (s *Server) readLoop(ws *websocket.Conn) {
  buf := make([]byte, 1024)
  for {
    n, err := ws.Read(buf)
    if err != nil {
      fmt.Println("read error:", err)
      continue
    }
    data := buf[:n]
    fmt.Println("received data:", string(data))
    ws.Write([]byte("thank you for the msg"))
  }
}

func main() {
  s := NewServer()
  http.Handle("/ws", websocket.Handler(s.handleWS))
  http.ListenAndServe(":8911", nil)
}

react使用范例

//点击button触发scan() function
const scan = ()=>{
    let ws = new WebSocket("ws://127.0.0.1:9999/location")
    ws.onmessage = e=>{
      setScanBtnIsDisabled(true)
      console.log(e.data)
      setScanData(e.data)
      if (e.data==="success"){
        setScanBtnIsDisabled(false)
        ws.close()
      }
    }
    
    ws.onopen = () => {
      ws.send("LOCATION")
    }
  }