Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@WesThorburn
Created May 14, 2018 22:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WesThorburn/c44a571c96512399ca6688d7763db739 to your computer and use it in GitHub Desktop.
Save WesThorburn/c44a571c96512399ca6688d7763db739 to your computer and use it in GitHub Desktop.
Sending binary messages between client and server using uWS
var socket = new WebSocket("ws://localhost:3000");
socket.binaryType = "arraybuffer";
socket.onopen = function(){
var arrayBufferMessage = stringToArrayBuffer("Test message from client");
socket.send(arrayBufferMessage);
};
socket.onmessage = function(e){
console.log(arrayBufferToString(e.data));
}
function stringToArrayBuffer(string){
var buffer = new ArrayBuffer(string.length);
var bufferView = new Uint8Array(buffer);
for(var i = 0; i < string.length; i++){
bufferView[i] = string.charCodeAt(i);
}
return bufferView;
}
function arrayBufferToString(arrayBuffer){
return String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
}
#include <uWS/uWS.h>
#include <string>
#include <iostream>
int main(){
uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) {
std::string receivedMessage(message, length);
std::cout << receivedMessage << std::endl;
ws->send("Reponse from server", uWS::OpCode::BINARY);
});
if (h.listen(3000)) {
h.run();
}
}
@johnroper100
Copy link

does this work if I just want to send a string with text, maybe with json?

@WesThorburn
Copy link
Author

WesThorburn commented May 17, 2018

If you're just wanting to send straight text, skip the whole stringToArrayBuffer() step on the client side and don't set a socket.binaryType. On the server side, you won't need uWS::OpCode::BINARY.

I would advise not sending JSON via websockets, JSON contains a lot of bloat and you'll end up consuming far more resources than necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment