代码拉取完成,页面将自动刷新
package main
import (
"log"
"net/http"
socketio "github.com/googollee/go-socket.io"
)
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Max-Age", "3600")
// Handle preflight requests
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
log.Println("go...")
server := socketio.NewServer(nil)
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
log.Println("Client connected:", s.ID())
return nil
})
server.OnDisconnect("/", func(s socketio.Conn, reason string) {
log.Println("Client disconnected:", s.ID(), "Reason:", reason)
})
server.OnError("/", func(s socketio.Conn, e error) {
log.Println("Socket.IO error for client:", s.ID(), "Error:", e)
})
server.OnEvent("/", "message", func(s socketio.Conn, msg string) {
log.Println("Received message from client:", msg)
s.Emit("response", "Message received: "+msg)
})
go func() {
if err := server.Serve(); err != nil {
log.Fatalf("Socket.IO server failed: %v", err)
}
}()
defer server.Close()
http.Handle("/", withCORS(http.FileServer(http.Dir("./static"))))
http.Handle("/socket.io/", withCORS(server))
ipAddress := "192.168.0.25"
port := "8877"
address := ipAddress + ":" + port
log.Printf("Serving at ws://%s...", address)
if err := http.ListenAndServe(address, nil); err != nil {
log.Fatalf("Failed to start HTTP server: %v", err)
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。