Receive Parsed Web Socket Messages
Last updated on
Use the following function to receive a parsed websocket message from the server:
- Go
- Python
- Java
//messageHandler is callback function how to handle incoming ws message
var messageHandler = func(dataByte []byte) {
message, err := parser.UnmarshalResponse(dataByte)
if err != nil {...}
// print all incoming message type
logrus.Infof("Message type: %v", message.Type())
marshal, err := json.Marshal(message)
if err != nil {...}
// print all incoming message content
logrus.Infof("Message content: %v", string(marshal))
// if you want to specify the message type and write logic for each of it
switch message.Type() {
case model.TypeNotificationMessage:
notificationMsg := message.(model.NotificationMessage)
logrus.Infof("Notification is coming from %s to %s", notificationMsg.From, notificationMsg.To)
case model.TypeKickResponse:
kickMessage := message.(model.KickResponse)
logrus.Infof("Message id is: %s", kickMessage.MessageID)
}
}
async def receive_and_send_formatted_web_socket_messages():
from accelbyte_py_sdk.core import get_access_token, get_base_url
from accelbyte_py_sdk.core import WebsocketsWSClient
base_url, error = get_base_url()
if error:
exit(1)
access_token, error = get_access_token()
if error:
exit(1)
client = WebsocketsWSClient(
uri=base_url,
access_token=access_token
)
# 1 Register a listener for received web socket messages.
client.listeners.append(on_receive)
await client.connect()
async def on_receive(message: str):
from accelbyte_py_sdk.api.lobby.wss_models import parse_wsm
# 2. Parse received web socket message.
result, error = parse_wsm(message)
if error:
print(error)
final String request_id = GenerateRandomId(64);
final CountDownLatch response = new CountDownLatch(1);
final Map<String,String> parsedResponseWSM = new HashMap<>();
WebSocketListener listener = new WebSocketListener() {
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
if (response.getCount() > 0) {
parsedResponseWSM .putAll(net.accelbyte.sdk.core.util.Helper.parseWSM(text));
response.countDown();
}
}
};
OkhttpWebSocketClient ws = OkhttpWebSocketClient.create(
new DefaultConfigRepository(),
DefaultTokenRepository.getInstance(),
listener);
String requestMessage = PartyCreateRequest.builder()
.id(requestId)
.build()
.toWSM();
ws.sendMessage(requestMessage);
response.await(10, TimeUnit.SECONDS);