Created
November 18, 2017 11:15
-
-
Save AnatolyShirykalov/271095bd96fdd0f375bd6daa4bc985cb to your computer and use it in GitHub Desktop.
game server socket io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/gin-gonic/gin" | |
"github.com/googollee/go-socket.io" | |
"log" | |
"reflect" | |
"strings" | |
) | |
func onAction(s socketio.Socket, data interface{}) { | |
v := reflect.ValueOf(data) | |
typeWithPrefix, ok := v.Interface().(map[string]interface{})["type"] | |
if !ok { | |
log.Println(v) | |
} | |
tp := strings.Replace(typeWithPrefix.(string), "server/", "", 1) | |
v.SetMapIndex(reflect.ValueOf("type"), reflect.ValueOf(tp)) | |
ret := v.Interface() | |
s.Emit("action", ret) | |
s.BroadcastTo("chat", "action", ret) | |
} | |
func onJoin(s socketio.Socket, roomId string) { | |
s.Join(roomId) | |
} | |
func main() { | |
server, err := socketio.NewServer(nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
server.On("connection", func(so socketio.Socket) { | |
log.Println("on connection") | |
so.Join("chat") | |
so.On("chat message", func(msg string) { | |
log.Println("emit:", so.Emit("chat message", msg)) | |
so.BroadcastTo("chat", "chat message", msg) | |
}) | |
so.On("action", onAction) | |
so.On("join", onJoin) | |
so.On("disconnect", func() { | |
log.Println("on disconnect") | |
for _, roomId := range so.Rooms() { | |
so.BroadcastTo(roomId, "leaving", so.Id) | |
} | |
}) | |
}) | |
server.On("error", func(so socketio.Socket, err error) { | |
log.Println("error:", err) | |
}) | |
r := gin.Default() | |
r.LoadHTMLFiles("index.html") | |
r.GET("/", func(c *gin.Context) { | |
c.HTML(200, "index.html", nil) | |
}) | |
r.Static("/js", ".") | |
r.GET("/socket.io/", gin.WrapH(server)) | |
r.Run("localhost:12312") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> | |
<script src="./js/socket.io.js"></script> | |
</head> | |
<body> | |
<h3>WebSocket Go</h3> | |
<pre id="output"></pre> | |
<script> | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment