Diarkis サーバーは、他のサーバーにリクエストメッセージを送信し、リクエストに対するレスポンスを受け取ることができます。
Diarkisサーバーは、リクエストとレスポンス形式のメッセージを送受信することができます。
これは、複数のDiarkisサーバーが動作を調整し、データを交換する必要がある場合に有効です。
ハンドラ関数を定義する方法
// import "github.com/Diarkis/diarkis/mesh"
// import "github.com/Diarkis/diarkis/datacapsule"
// import "fmt"
// You must define the handler function when the server process starts
var myCommandID uint16 = 1024
mesh.HandleCommand(myCommandID, myCommandHandler)
func myCommandHandler(data map[string]interface{}) ([]byte, error) {
myName := mesh.GetString(data, "myName")
myScheduleBytes := mesh.GetBytes(data, "mySchedule")
// Reconstruct mySchedule data created by datacapsule
mySchedule, err := datacapsule.Unpack(myScheduleBytes)
if err != nil {
// handle the error....
}
appointments := mySchedule.GetAsArray("appointments")
for _, item := range appointments {
date := item.(map[string]string)["date"]
title := item.(map[string]string)["title"]
fmt.Printf("Appointment: Date: %s Title: %s", date, title)
}
// Add a new appointment and send it back as response
appointments = append(appointments, map[string]{ "date": "14/2/2022", "Valentines Day" })
// Update mySchedule
mySchedule.SetAsArray("appointments", appointments)
response := make(map[string]interface{})
response["updatedMySchedule"] = datacapsule.Pack(mySchedule)
return mesh.CreateReturnBytes(response)
}
リクエストの送信とレスポンスの受信方法
The response will be received by the callback you assign when you send a request.
// import "github.com/Diarkis/diarkis/server"
// import "github.com/Diarkis/diarkis/mesh"
// import "github.com/Diarkis/diarkis/datacapsule"
var myCommandID uint16 = 1024
// Get all UDP server addresses
udpServerAddresses := mesh.GetNodeAddressesByType(server.UDPType)
if len(udpServerAddresses) == 0 {
// no UDP servers found....
return
}
// choose one UDP server from the list
udpServerAddress := udpServerAddresses[0]
// create the data to send
data := make(map[string]interface{})
data["myName"] = "Jon"
mySchedule := datacapsule.NewCapsule()
appointments := make([]map[string]string, 2)
appointments[0] = map[string]{ "date": "01/01/2022", "title": "New Year Party" }
appointments[1] = map[string]{ "date", "25/12/2022", "title": "Christmas Party" }
mySchedule.SetAsArray("appointments", appointments)
data["mySchedule"] = datacapsule.Pack(mySchedule)
mesh.SendRequest(myCommandID, udpServerAddress, data, handleMyResponse)
func handleMyResponse(response map[string]interface{}) {
updatedMyScheduleBytes := mesh.GetBytes(response, "updatedMySchedule")
updatedMySchedule, err := mesh.Unpack(updatedMyScheduleBytes)
// Do something awesome here!
}