transferring files with javascript through websockets

前端 未结 2 2145
忘了有多久
忘了有多久 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:10

    What you're trying to do isn't possible. WebSocket can only operate in a client mode; it cannot accept connections from another WebSocket client (such as another browser).

    It is possible to hook WebSocket clients to one another through a server, but at that point it's no longer really peer-to-peer, so I'm not sure if that's really useful or interesting anymore.

    See: Will Websockets allow a server to run in the browser?

    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题