Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复链接异常的问题 #3

Merged
merged 3 commits into from
Jul 23, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
修复链接异常的问题
  • Loading branch information
bydmm committed Jul 23, 2019
commit ca91e02b09ce4fa37864b088dccf204fe5fd7698
4 changes: 3 additions & 1 deletion 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 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