server.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package game
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "github.com/gin-gonic/gin"
  9. "github.com/gorilla/websocket"
  10. )
  11. //数据包-用于前后端的RPC调用
  12. type dataPack struct {
  13. Type int32 `json:"type"`
  14. Func string `json:"func"`
  15. Args []interface{} `json:"args"`
  16. }
  17. //CheckOrigin防止跨站点的请求伪造
  18. var upGrader = websocket.Upgrader{
  19. CheckOrigin: func(r *http.Request) bool {
  20. //直接通过,因为目前还没必要做检测
  21. return true
  22. },
  23. }
  24. //Socket处理器
  25. func socketHandler(c *gin.Context) {
  26. ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  27. if err != nil {
  28. return
  29. }
  30. se := createEntity(ws)
  31. defer invokeFunc(se, "OnDestroy")
  32. defer ws.Close()
  33. invokeFunc(se, "OnLoad")
  34. for {
  35. _, message, err := ws.ReadMessage()
  36. if err != nil {
  37. break
  38. }
  39. dp := dataPack{}
  40. json.Unmarshal(message, &dp)
  41. invokeFuncByDataPack(se, &dp)
  42. }
  43. }
  44. //定义函数-创建Socket实体
  45. type CreateEntity func(conn *websocket.Conn) interface{}
  46. //自定义函数-创建Socket实体
  47. var createEntity CreateEntity
  48. //开启服务监听
  49. func StartServer(port int, path string, createEntityFunc CreateEntity) {
  50. createEntity = createEntityFunc
  51. r := gin.Default()
  52. r.GET(path, socketHandler)
  53. r.Run(":" + strconv.Itoa(port))
  54. }
  55. //向客户端发送数据包
  56. func SendPackFunction(ws *websocket.Conn, func_ string, args ...interface{}) {
  57. dp := dataPack{Func: func_, Args: args, Type: 1}
  58. ws.WriteJSON(&dp)
  59. }
  60. //通过反射调用函数
  61. func invokeFunc(obj interface{}, func_ string, args ...interface{}) {
  62. ctx := reflect.ValueOf(obj)
  63. if strings.Contains(func_, ".") {
  64. func_Split := strings.Split(func_, ".")
  65. ctx = ctx.FieldByName(func_Split[0])
  66. func_ = func_Split[1]
  67. }
  68. method := ctx.MethodByName(func_)
  69. if !method.IsValid() {
  70. return
  71. }
  72. argsLen := len(args)
  73. argsList := make([]reflect.Value, argsLen)
  74. for i := 0; i < argsLen; i++ {
  75. argsList[i] = reflect.ValueOf(args[i])
  76. }
  77. method.Call(argsList)
  78. }
  79. //检测开关-在远程调用前是否进行合法检测
  80. var CheckServiceFuncMapBeforInvoke = false
  81. //为了防止非法远程调用,只允许调用Map中记录的方法
  82. var ServiceFuncMap = make(map[string]bool)
  83. //根据客户端传来的RPC数据包调用指定的函数
  84. func invokeFuncByDataPack(obj interface{}, dp *dataPack) {
  85. if dp.Type == 1 {
  86. if !CheckServiceFuncMapBeforInvoke || ServiceFuncMap[dp.Func] {
  87. invokeFunc(obj, dp.Func, dp.Args...)
  88. }
  89. }
  90. }