5

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 transfer files with javascripts and websockets? any examples on how to integrate my c++ program into javascript would be appreciated. thanks.

DasBoot
  • 707
  • 3
  • 15
  • 37

2 Answers2

7

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"
kanaka
  • 70,845
  • 23
  • 144
  • 140
1

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?

Community
  • 1
  • 1
  • 1
    thanks, if you can provide examples on how to do it through a server it would be appreciated. =) – DasBoot Jul 09 '12 at 06:33