Skip to content

Commit

Permalink
Merge pull request #3 from bydmm/dev
Browse files Browse the repository at this point in the history
修复链接异常的问题
  • Loading branch information
bydmm authored Jul 23, 2019
2 parents 2a5404a + ca91e02 commit 97a5626
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 16 deletions.
6 changes: 4 additions & 2 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func RunClient(addr string, room string, token string) {
u := url.URL{
Scheme: "ws",
Host: addr,
Path: fmt.Sprintf("ws/%s/%s", token, room),
Path: fmt.Sprintf("ws/%s/join", token),
}
log.Printf("connecting to %s", u.String())

Expand All @@ -36,6 +36,8 @@ func RunClient(addr string, room string, token string) {

go func() {
defer close(done)
c.WriteMessage(websocket.TextMessage, []byte(room))

for {
_, message, err := c.ReadMessage()
if err != nil {
Expand All @@ -51,7 +53,7 @@ func RunClient(addr string, room string, token string) {
err = json.Unmarshal([]byte(msg.Msg), &v)
if err == nil {
body, _ := json.MarshalIndent(v, "", " ")
fmt.Printf("%s %s\n %s\n", time, msg.Client, body)
fmt.Printf("========================== %s %s ==========================\n %s\n", time, msg.Client, body)
} else {
fmt.Printf("%s %s\n %s\n", time, msg.Client, msg.Msg)
}
Expand Down
33 changes: 19 additions & 14 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,35 +24,40 @@ func HandleLogin(room string, s *melody.Session) {
// RunServer 运行服务器
func RunServer() {
MelodyInit()
token := os.Getenv("JIODESECRET_TOKEN")

token := os.Getenv("JIODE_SECRET_TOKEN")
if token == "" {
token = util.RandStringRunes(6)
}

r := gin.Default()

r.GET(fmt.Sprintf("/ws/%s/:room", token), func(c *gin.Context) {
Melody.HandleRequest(c.Writer, c.Request)
Melody.HandleConnect(func(s *melody.Session) {
fmt.Println("用户连接")
HandleLogin("", s)
})

Melody.HandleConnect(func(s *melody.Session) {
HandleLogin(c.Param("room"), s)
})
Melody.HandleDisconnect(func(s *melody.Session) {
formUser := clients.GetUser(s)
fmt.Println("用户退出房间" + formUser.Room())
clients.Delete(s)
})

Melody.HandleMessage(func(s *melody.Session, msg []byte) {
formUser := clients.GetUser(s)
Melody.BroadcastFilter(msg, func(s *melody.Session) bool {
toUser := clients.GetUser(s)
return toUser != nil && toUser.room == formUser.room
})
})
Melody.HandleMessage(func(s *melody.Session, msg []byte) {
user := clients.GetUser(s)
user.SetRoom(string(msg))
fmt.Println("用户进入房间" + user.Room())
})

r.GET(fmt.Sprintf("/ws/%s/join", token), func(c *gin.Context) {
Melody.HandleRequest(c.Writer, c.Request)
})

r.POST(fmt.Sprintf("/api/%s/:room", token), func(c *gin.Context) {
room := c.Param("room")
if room == "" {
return
}

var jsonBody model.Message
c.BindJSON(&jsonBody)
msg, _ := json.Marshal(jsonBody)
Expand Down

0 comments on commit 97a5626

Please sign in to comment.