1.第一步引入go package,go get github.com/googollee/go-socket.io。
//main.go文件内容
package main
import (
"fmt"
socketio "github.com/googollee/go-socket.io"
"log"
"net/http"
)
var conw []socketio.Conn = make([]socketio.Conn, 0)
func main() {
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
conw = append(conw, s)
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)
//此为群推所有在线人员
for _, val := range conw {
val.Emit("reply", "have "+msg)
}
})
server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
s.SetContext(msg)
return "recv " + msg
})
server.OnEvent("/", "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(e error) {
fmt.Println("meet error:", e)
})
server.OnDisconnect("/", func(s socketio.Conn, msg string) {
fmt.Println("closed", msg)
})
go server.Serve()
defer server.Close()
http.Handle("/socket.io/", server)
http.Handle("/", http.FileServer(http.Dir("./asset")))
log.Println("Serving at localhost:8000...")
log.Fatal(http.ListenAndServe(":8000", nil))
}
2.第二部执行 go run main.go
3.nginx 服务器配置
location ^~ /socket.io {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
proxy_pass http://localhost:8000;
}
4.浏览器访问 localhost/index.html
本人实测无问题,只是演示简单的go,socket.io实现,点对点、群聊功能后续继续优化。如有问题联系qq:1522263421