transferring files with javascript through websockets

前端 未结 2 2144
忘了有多久
忘了有多久 2021-02-10 03:46

hello i am trying to transfer files. I have some programs converting files to binary and transferring them over a network with c++. I was wondering if i would be able to transfe

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-10 04:20

    Javascript has two new binary types: typed arrays (arraybuffers) and Blobs (basically files).

    WebSockets support sending and receiving typed arrays and blobs.

    To transfer data between two browsers using WebSockets you will need a server for them both to connect to (browser WebSocket support is client only at this point).

    If you have an existing server in C++ that handles file transport then you should be able to add WebSocket server support to it fairly easily. You can find WebSocket client and server implementations on this page: http://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations

    In JavaScript to establish a connection to a WebSocket server you do something like this:

    ws = new WebSocket("ws://100.101.102.103");
    

    The send() method support normal strings, typed arrays or blobs. Sending typed arrays and blobs will result in the frame(s) received by the server as binary frames (opcode = 2).

    ws.send(myTypedArray);
    

    To receive messages you register a message handler:

    ws.onmessage = function (evt) {
        console.log("Got ws message: " + evt.data);
    };
    

    If the server sends a binary frame/message then the onmessage data property of the event will contain either a typed array or blob depending on the setting of the binaryType attribute. You can change the type of the binary data that is received like this:

    ws.binaryType = "blob"; // or "arraybuffer"
    

提交回复
热议问题