Parsing Match Loop message (Example code broken?)

I’m trying to send data objects to the server to modify the state of server authoritive matches. I understand the concept - I use SendMatchStateAsync, plugin a data object and parse it on the other end (MatchLoop)

Using the example code however, throws an error. Here it is from the Nakama project example:

let msg = {} as MoveMessage;
try {
msg = JSON.parse(message.data);
}

It seems however, that you cannot simply parse the data, since it is of type UInt8Array

Am I missing something? Or is there some other syntax/typing that works to properly peel out the data?

You are just missing one little thing

msg = JSON.parse(String(message.data));

Thanks for the reply,

So you can just cast the Uint8Array directly to string? This must mean that the example project is broken.

I think it’s outdated, the data before was returned as string but when passing bytes to the MatchState the data was getting corrupted, so they changed it to Uint8Array on some of the latests releases

2 Likes

@RunGrizzly The latest release of Nakama server (last one before Christmas) did change the field type which is returned to the runtime to provide better performance when the type does not need to be coerced into a string. We’ll update the project template. Thanks for the heads up :pray:

Awesome, thanks for the clarification.

Update: Casting to string does not work at all and simply throws the same error. The matchloop only sees the message data as [ObjectArrayBuffer]

The data object I’m trying to parse is a very simple struct with two integers.

A little digging tells me that the problem requires the TextDecoder JS class to create a string from the Array - but when implemented it triggers an early execute and logs this:

Match Loop:

logger.debug('Match mod received with raw data: ’ + message.data);
var c = String(message.data);
logger.debug('Data as string looks like: ’ + c);
var enc = new TextDecoder(“utf-8”);
var d = enc.decode(message.data);
logger.debug('Decoded data looks like: ’ + d);

Throws at decoder:

{“level”:“warn”,“ts”:“2022-01-05T22:51:29.326Z”,“caller”:“server/match_handler.go:295”,“msg”:“Stopping match after error from match_loop execution”,“mid”:“f91c836a-bc0f-4625-a418-4e401282e6e8”,“tick”:1,“error”:“ReferenceError: TextDecoder is not defined at matchLoop (index.js:94:27(72))”}

I wonder what the recommended process is here, considering the example is outdated, there must be a recommended way to pass data objects as messages to the match loop.

@RunGrizzly we’ve updated the template: GitHub - heroiclabs/nakama-project-template: An example project on how to set up and write custom server code in Nakama server. (see the changes here).

Please note the use of the runtime provided function nk.binaryToString to convert the match data to a string.

Perfect! Just the method I’ve been looking for.