1. 项目地址:
    https://github.com/googollee/go-socket.io

  2. 示例代码:

    1. go 服务器:

      package main
      import (
      "fmt"
      "log"
      "net/http"
      "github.com/googollee/go-socket.io"
      )
      func main() {
      server, err := socketio.NewServer(nil)
      if err != nil {
       log.Fatal(err)
      }
      server.OnConnect("/", func(s socketio.Conn) error {
       s.SetContext("")
       fmt.Println("connected:", s.ID())
       return nil
      })
      server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
       fmt.Println("notice:", msg)
       s.Emit("reply", "have "+msg)
      })
      server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
       s.SetContext(msg)
       return "recv " + msg
      })
      server.OnEvent("/", "bye", func(s socketio.Conn) string {
       last := s.Context().(string)
       s.Emit("bye", last)
       s.Close()
       return last
      })
      server.OnError("/", func(s socketio.Conn, e error) {
       fmt.Println("meet error:", e)
      })
      server.OnDisconnect("/", func(s socketio.Conn, reason string) {
       fmt.Println("closed", reason)
      })
      go server.Serve()
      defer server.Close()
      http.HandleFunc("/socket.io/", func(w http.ResponseWriter, r *http.Request) {
       origin := r.Header.Get("Origin")
       log.Println("origin",origin)
       w.Header().Set("Access-Control-Allow-Origin", origin)
       w.Header().Set("Access-Control-Allow-Credentials", "true")
      
       server.ServeHTTP(w, r)
      })
      log.Println("Serving at localhost:8000...")
      log.Fatal(http.ListenAndServe(":8000", nil))
      }
    2. go 客户端:

      package main
      import (
      "bufio"
      "github.com/zhouhui8915/go-socket.io-client"
      "log"
      "os"
      )
      func main() {
      opts := &socketio_client.Options{
       Transport: "websocket",
       Query:     make(map[string]string),
      }
      uri := "http://localhost:8000/socket.io/"
      client, err := socketio_client.NewClient(uri, opts)
      if err != nil {
       log.Printf("NewClient error:%v\n", err)
       return
      }
      client.On("error", func() {
       log.Printf("on error\n")
      })
      client.On("connection", func() {
       log.Printf("on connect\n")
      })
      client.On("message", func(msg string) {
       log.Printf("on message:%v\n", msg)
      })
      client.On("disconnection", func() {
       log.Printf("on disconnect\n")
      })
      reader := bufio.NewReader(os.Stdin)
      for {
       data, _, _ := reader.ReadLine()
       command := string(data)
       client.Emit("notice", command)
       log.Printf("send message:%v\n", command)
      }
      }
    3. js 客户端:

      <!doctype html>
      <html>
      <head>
      <title>Socket.IO chat</title>
      <style>
       * {
           margin: 0;
           padding: 0;
           box-sizing: border-box;
       }
      
       body {
           font: 13px Helvetica, Arial;
       }
      
       form {
           background: #000;
           padding: 3px;
           position: fixed;
           bottom: 0;
           width: 100%;
       }
      
       form input {
           border: 0;
           padding: 10px;
           width: 90%;
           margin-right: .5%;
       }
      
       form button {
           width: 9%;
           background: rgb(130, 224, 255);
           border: none;
           padding: 10px;
       }
      
       #messages {
           list-style-type: none;
           margin: 0;
           padding: 0;
       }
      
       #messages li {
           padding: 5px 10px;
       }
      
       #messages li:nth-child(odd) {
           background: #eee;
       }
      </style>
      </head>
      <body>
      <ul id="messages"></ul>
      <form action="">
      <input id="m" autocomplete="off"/>
      <button>Send</button>
      </form>
      <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
      <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
      <script>
      var socket = io("http://localhost:8000");
      // socket.emit('msg', 'hello');
      var s2 = io("/chat");
      socket.on('reply', function (msg) {
       $('#messages').append($('<li>').text(msg));
      });
      $('form').submit(function () {
       s2.emit('msg', $('#m').val(), function (data) {
           $('#messages').append($('<li>').text('ACK CALLBACK: ' + data));
       });
       socket.emit('notice', $('#m').val());
       $('#m').val('');
       return false;
      });
      </script>
      </body>
      </html>
文档更新时间: 2020-08-08 20:40   作者:lee