How to receive websocket messages from Vert.x server in Javascript?

I am trying to create an http server including websockets with Vert.x in Java while writing a client in Javascript without vertx.js. I avoid using Vert.x in the client because it has to remain in the browser (tools like browserfy were unable to convert the CommonJS standard Vert.x into code that browsers can use).

After completing the test code for the server and client, I tried a simple example of sending a message to the server, receiving its data, and responding with a custom response. The server received the message and was able to read the content. However, the client received the message without receiving the intended content. Client was unable to convert event data received with websocket to string (no string data at all?). Using indexof.js to determine the size of the event data bytes that got a constant size of 34 bytes after changing the content sent by the server multiple times. I tried to use writeMessage as well as write method on server to send data to client-websocket. The results are the same.

Why is my client only getting constant size data on the website and how do I get it to work?

Thanks for your suggestions!

EDIT: I am swapping methods write

and writeMessage

using writeFrame

. Using writeFrame

can send binary data as well as plain text. Sending text this way from a Java based server to a Javascript client works fine. I still don't know how to handle binary messages on clients, but that would be beneficial. Although text messages work, it is assumed that they are still the same size (34 bytes). I thought the resulting data object would be different in size, but it looks like it's just an object pointing to the actual data somewhere.

-------------------------------------------- ----

The client code was written during (successful) tests using Java Servlets and Web sites:

var wsUri = "ws://" + document.location.host + document.location.pathname + "chat";

var websocket = new WebSocket(wsUri);
websocket.onerror = function(evt) { onError(evt) };
websocket.onopen = function (evt) { onOpen(evt) };

function onError (evt)
{
    debugMessage('<span style="color: red;">ERROR:</span> ' + evt.data);
}

function onOpen (evt)
{
//    debugMessage("Connected to " + wsUri);
    debugMessage("GOTCHA!");
}

websocket.onmessage = function (evt) { onMessage(evt) };

function onMessage (evt)
{
    debugMessage(evt.toString());
    debugMessage(evt.data.toString());
    debugMessage(sizeof(evt.data));
}

function sendMessage (msg)
{
    websocket.send(msg);
}

function sendDebugMessage ()
{
    websocket.send("Hiho Wursty!");
    debugMessage("Did send Wursty-message.");
}

      

Server server according to official Vert.x documentation and also another other online tutorial :

server = vertx.createHttpServer();

server.requestHandler(request -> {
    handleRequest(request);
});

server.websocketHandler(ws -> {
    print("Websocket-handshake...");
    print("path = " + ws.path());
    print("uri = " + ws.uri());
    print("localAdress = " + ws.localAddress().toString());
    print("remoteAddress = " + ws.remoteAddress());
    print(ws.toString());

    if (!ws.path().equals("/chat")) {
        ws.reject();
    } else {
        SharedData sd = vertx.sharedData();
        LocalMap<String, String> wsChatSessions =
                sd.getLocalMap("ws.chat.sessions");

        wsChatSessions.put(ws.textHandlerID(), ws.toString());

        ws.closeHandler(ch -> {
            print("Closing ws-connection to client " + ws.textHandlerID());
            wsChatSessions.remove(ws.textHandlerID());
        });

        ws.handler(new Handler<Buffer>(){
            @Override
            public void handle(final Buffer data) {
                String msg = data.getString(0, data.length());
                print("Message from ws-client " + ws.textHandlerID() 
                        + ": " + msg);
                Buffer resp = Buffer.buffer();
                resp.appendString("O Ding Dong asd asda sdasd a"
                        + "asdasd asd asdasda sdas dasd adads asd as"
                        + "as dasd asd asd asd asdasd asdasdasd "
                        + "asdasd asd asd asd asd asda sdasd asd !");
                ws.writeMessage(resp);
                ws.write(resp);
            }
        });
    }
});

server.listen(port, res -> {
    if (res.succeeded()){
        print("Listening...");
    } else{
        print("Failed to bind! -> Server is not listening"
            + " to incoming client connections.");
    }
});

      

+3


source to share


1 answer


The reason that I only got a 0-byte messages was relatively simple: Javascript-websocket can determine the type (binary) data obtained using a WebSocket server binaryType

. The default is set to "blob"

. In my case, I was supposed to get massive buffers. Thus, by setting the option, the webcam transmitted data as expected:

websocket.binaryType = "arraybuffer";

      

To use it, you still need to create an array from arraybuffer. In my case, I created an array of unsigned 8-bit integers:



var dataBytes = new Uint8Array(evt.data);

      

The data is now ready for processing with the following code.

+4


source







All Articles