bonza The backend development engineers

go socket.io使用过程中的坑

2021-05-28
HyG
本文 2046 字,阅读全文约需 6 分钟

示例代码

默认go的socket.io包是不跨域的,网上很多示例,包括官方的,都没有跨域的解决方式,最后,在GitHub上看到这个解决方案,亲测可行,记录一下。


package main

import (
	"fmt"
	"github.com/googollee/go-socket.io/engineio"
	"github.com/googollee/go-socket.io/engineio/transport"
	"github.com/googollee/go-socket.io/engineio/transport/polling"
	"github.com/googollee/go-socket.io/engineio/transport/websocket"
	"log"
	"net/http"
	"time"

	socketIo "github.com/googollee/go-socket.io"
)

func main() {
    //必须有这一段,否则跨域请求统统失败,这个函数的意思是允许跨域
	allowOrigin := func(r *http.Request) bool {
		return true
	}
	server, _ := socketIo.NewServer(&engineio.Options{
		Transports: []transport.Transport{
			&polling.Transport{
				Client: &http.Client{
					Timeout: time.Minute,
				},
				CheckOrigin: allowOrigin,
			},
			&websocket.Transport{
				CheckOrigin: allowOrigin,
			},
		},
	})

	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("/", "imei", func(s socketIo.Conn, msg interface{}) {
		//types := reflect.TypeOf(msg)
		fmt.Println("imei:", msg)

		switch msg.(type) {
		case string:
			panic("sdfdsf")
		case map[string]interface{}:
			fmt.Println("imei:", msg.(map[string]interface{})["imei"])
		default:
			panic("dd")
		}
		s.Emit("imei", "have ")
	})

	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)
		err := s.Close()
		if err != nil {
			panic("exception")
		}
		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 func() {
		err := server.Serve()
		fmt.Println(err)
	}()
	defer func() {
		err := server.Close()
		fmt.Println(err)
	}()

	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("../asset")))

	log.Println("Serving at localhost:8000...")
	log.Fatal(http.ListenAndServe(":8000", nil))
}

原文地址 https://blog.bonza.cn/2021/05/28/go-socket.io/

Comments

Content