I'm using the node.js echo-server version in https://www.npmjs.com/package/websocket with the websockets sample plugin in https://www.assetstore.unity3d.com/en/#!/content/38367. The messages are received correctly in both the server and the client (when echoed) but they are interpreted as binary data, not as utf8 string.
Here is the relevant code.
Unity client:
public class EchoTest : MonoBehaviour {
public string uri = "ws://localhost:8080/";
IEnumerator Start () {
WebSocket w = new WebSocket(new Uri(uri));
yield return StartCoroutine(w.Connect());
w.SendString("Hi there");
string reply = w.RecvString();
if (reply != null) {
Debug.Log ("Received: "+reply);
}
w.Close();
}
}
public class WebSocket {
...
public void SendString(string str) {
Send(Encoding.UTF8.GetBytes (str));
}
...
}
Nodejs server:
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('NEVER CALLED');
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
console.log(encode_utf8(message.binaryData)); // if manually converted to utf8 the string is showed correctly in server console
}
});
});
Does anyone know how to send data as utf8 strings to a node.js server?
Thanks in advance.
↧