Skip to content

Package Usage

Dhruvik edited this page Nov 15, 2024 · 1 revision

This is the example from wordsbattle codebase which runs miniwordgames.com

NewMeshServer

Setup the server where it will have all clients and rooms information , roomdata is your information through which a room global will be created and holds the information which you can access interface .

roomdata := &game.RoomData{RandomRooms: []string{}}
ms := simplysocket.NewMeshServer("cowgame", &simplysocket.MeshServerConfig{DirectBroadCast: false}, roomdata)
// initialize websocket link cowgame connection clash of words
r.HandleFunc("/wsmesh", func(w http.ResponseWriter, r *http.Request) {
	simplysocket.ServeWs(ms, w, r)
})

link to code

HandleRoomData

Implement HandleRoomData function in your codebase . This function is the go routine which runs when a newmeshserver is created . The objects will have the property which you wanted to give and can be accessed . In below funciton RoomData is the struct of the object of newMeshServer created .

func (r *RoomData) HandleRoomData(room simplysocket.Room, server simplysocket.MeshServer) {
	roomname := room.GetRoomSlugInfo()
	r.Slug = roomname
	log.Println("Handeling data Server for ", roomname, server.GetGameName())
	// ticker := time.NewTicker(5 * time.Second)
	// defer ticker.Stop()
	for {
		select {
		case message, ok := <-room.ConsumeRoomMessage():
			//log.Println(server.GetRooms())
			if !ok {
				log.Println("Channel closed. Exiting HandleRoomData for", roomname)
			}
			log.Println("Room data ", message)

			if message.Target == roomname {
				r.handleServermessages(room, server, message)
			}

		case clientevent := <-room.EventTriggers():
			log.Println("Event triggered", clientevent[0], clientevent[1], clientevent[2], room.GetRoomSlugInfo())

		// case <-ticker.C:
		// 	log.Println("Room activity server", room.GetRoomSlugInfo(), r.Slug)

		case <-room.RoomStopped():
			log.Println("Room is stopped so stop the handler")
			return

		}
	}
}

link to code

room.GetRoomSlugInfo()

room.GetRoomSlugInfo() will give you the room id

room.GetRoomMakerInfo()

room.GetRoomMakerInfo() will give you the client id which created this room

room.GetClientsInRoom()

room.GetClientsInRoom() will return map[string]map[string]*client roomids->clientids check example

room.ConsumeMessage()

room.ConsumeMessage() will send messages from the client side to the server . It can be removed if you have a service which push the message .

room.EventTriggers()

room.EventTriggers() will send events it is string list where 1st is the event name which can be client-joined-room , client-left-room , 2nd part is the roomname , 3rd part is clientuniqid . This will help you to implement further logics like here in wordsbattle

room.RoomStopped()

room.RoomStopped() will notify room is stopped this will happen when no client is there in the room . Implement this in custom funciton for better go routine management .

simplysocket.Message{}

This is the standard Message struct which simplysocket process and push it . Keep the same struct pattern in client side as well Action: as same as a Title of message Target: Its a room id or client id MessageBody: map interface of message to be send isTargetClient: flag to send message to a client only

	res := &simplysocket.Message{
			Action:         "room-setting-applied",
			Target:         message.Target,
			MessageBody:    map[string]interface{}{"message": "Room settings applied successfully Player Limit:- " + message.MessageBody["player_limit"].(string) + " Time duration :-" + message.MessageBody["game_duration"].(string)},
			Sender:         "bot-of-the-room",
			IsTargetClient: false,
		}

room.BroadcastMessage(message)

room.BroadcastMessage(message) will broadcast the message . room will have the client list in it . This will push message to all clients in it but if it needs to be send to a particular client set IsTargetClient to true in message.

func (r *RoomData) FailToJoinRoomNotify(reason string, clientsinroom []string, room simplysocket.Room, server simplysocket.MeshServer) {
	reasonmsg := ""
	log.Println("Client removed", clientsinroom[2])
	if reason == "room-full" {
		reasonmsg = "Failed to join the room its occupied"
	}
	message := &simplysocket.Message{
		Action: "fail-join-room-notify",
		Target: clientsinroom[2],
		MessageBody: map[string]interface{}{
			"message": reasonmsg,
		},
		Sender:         "bot-of-the-room",
		IsTargetClient: true,
	}

	room.BroadcastMessage(message)
}

link to code

server.JoinClientRoom(roomname string, clientname string, rd RoomData)

server.JoinClientRoom(roomname string, clientname string, rd RoomData) :- This function takes roomname uniq id , client uniq slug id and a object of the struct which you have created . So the approach is simplysocket checks whether a room is already there a roomname which you added if not then it will use object and create a room and it will add your client . SimplySocket self initializes a room mesh-global where a client is automatically added . It contains list of all clients in it. This mechanism will help you to create different rooms with different properties to play with .

A room created with a object of particular struct must need to implement HandleRoomData . Incase of wordsbattle there are 2 type of rooms one which is mesh-global has its implementation) and a game room implementation .

case "join-room":
		//needed only if new room is needed
		rd := GameRoomData{
			IsRandomGame:     false,
			PlayerLimit:      int(message.MessageBody["playerlimit"].(float64)),
			ClientProperties: make(map[string]*ClientProps),
			GameEnded:        make(chan bool),
			Wordslist:        make(map[string]bool),
			Endtime:          1 * 60,
			Rounds:           0,
			TurnAttempted:    make(chan []string),
			HasGameStarted:   false,
			HasGameEnded:     false,
			ClientTurnList:   []*ClientProps{},
		}
		log.Println("JoinRoomAction ", message.Sender, message.MessageBody, room.GetRoomSlugInfo())
		roomname := message.MessageBody["roomname"].(string)
		server.JoinClientRoom(roomname, message.Sender, &rd)
		log.Println("request send to join a room")

link to code