2

I am new to websocket and I have been assigned an existing working chat module which, for now, just sends messages to other users. I have been asked to integrate feature where a user can send "attachments" to each other. FYI, I came across this link which says few point but I need more clarity.

My questions:

  1. What is the server-side requirement there for its implementation?
  2. Can someone provide a little elaborated answer? More codes rather than words are highly appreciated.
  3. Do I need to use use ng-file-upload for the same, DEMO
  4. Any relevant link for this question

UPDATE 1:

I tried implementing below code:

var input = document.querySelector('input[type=file]');

function readFile(event) {
    var ws_msg =  {content: event.target.result };
    // Here I call the ws.send method 
    send_chat_message($scope.sender, $scope.receiver , ws_msg );
}

function changeFile() {
    var file = input.files[0];
    var reader = new FileReader();
    reader.addEventListener('load', readFile);
    reader.readAsText(file);
}

input.addEventListener('change', changeFile);

Selecting a file automatically tries to send it over ws but for some weird reason, the WS connection is getting closed immediately.

halfer
  • 19,824
  • 17
  • 99
  • 186
Samuel
  • 1,128
  • 4
  • 14
  • 34
  • 1
    may be this can be usefull https://stackoverflow.com/questions/18571001/file-upload-using-angularjs and http://jsfiddle.net/f8Hee/1/ – gusaindpk Jul 06 '17 at 04:18
  • @gusaindpk: Thanks but my question is for websocket. how to send files via it. Any help here ? – Samuel Jul 06 '17 at 05:56
  • May be this will help you out.. https://stackoverflow.com/questions/11080112/large-file-upload-with-websocket – gusaindpk Jul 06 '17 at 09:27
  • @gusaindpk : please check the update – Samuel Jul 06 '17 at 18:45
  • I believe one thing you must consider is the `websocket.binarytype` setting. It took me some time to get it right, you can look at my code [here](https://github.com/heltonbiker/RoadScanner/blob/master/RoadScanner.html), I use this with a python server (take a look at the other files). – heltonbiker Jul 06 '17 at 18:53
  • @Samuel updated the ans let know if it helps :) – gusaindpk Jul 07 '17 at 05:20

1 Answers1

2

I have tried below sample code. I have used https://github.com/websockets/ws for web-socket server. and in HTML/jS I have modified code like below works fine. Steps are below. (Hope you have node installed).

  1. Create a folder and do a npm install --save ws
  2. Create a server.js file and add below code.

            const WebSocket = require('ws');
    
            const wss = new WebSocket.Server({ port: 8080 });
    
            wss.on('connection', function connection(ws) {
              ws.on('message', function incoming(message) {
                console.log('received: %s', message);
              });
    
              ws.send('something');
            });
    
  3. run node server using node server.js, your websocket server is up on localhost:8080

  4. In your browser js change code as below (you are using angular do the change accordingly later as per your requirement)

                var input = document.querySelector('input[type=file]');
            var socket = new WebSocket('ws://localhost:8080');
    
                socket.addEventListener('open', function (event) {
                    socket.send('Hello Server!');
                });
    
    
            function readFile(event) {
                var ws_msg =  {content: event.target.result };
                socket.send(ws_msg);
                // Here I call the ws.send method 
                //send_chat_message($scope.sender, $scope.receiver , ws_msg );
            }
    
            function changeFile() {
                var file = input.files[0];
                var reader = new FileReader();
                reader.addEventListener('load', readFile);
                reader.readAsText(file);
            }
    
            input.addEventListener('change', changeFile);
    
  5. load your JS/HTML and upload a file you should see to console logs in your node server console.

UPDATE:

you can update your node js server code:

            const WebSocket = require('ws');
            const fs = require('fs');

            const wss = new WebSocket.Server({ port: 8080 });


            wss.on('connection', function connection(ws) {
              ws.on('message', function incoming(message) {
                let data =  new Buffer(message);
                    fs.writeFile('new.png', data, 'binary', function (err) {
                        if (err) {
                            console.log("error")
                        }
                        else {
                            console.log("done")
                        }
                    });
              });

Reference: Create image from ArrayBuffer in Nodejs

              ws.send('something');
            });

And client(browser side js) code as:

            var input = document.querySelector('input[type=file]');
            var socket = new WebSocket('ws://localhost:8080');

                socket.addEventListener('open', function (event) {
                    socket.send('Hello Server!');
                });

            function readFile(e) {
                //var ws_msg =  {content: event.target.result };
                 var rawData = e.target.result;
                 socket.send(rawData);
                // Here I call the ws.send method 
                //send_chat_message($scope.sender, $scope.receiver , ws_msg );
            }

            function changeFile() {
                var file = input.files[0];
                var reader = new FileReader();  
                reader.addEventListener('load', readFile);
                reader.readAsArrayBuffer(file);
            }

            input.addEventListener('change', changeFile);
gusaindpk
  • 1,243
  • 2
  • 13
  • 31
  • 1
    Could I ask you to use real words as much as possible? "Your" is not harder to type than "ur", and the latter may get you downvotes. Writing does not have to be perfect here, but this is not Facebook `:-)`. – halfer Jul 07 '17 at 10:00
  • 1
    Thanks for your edit @halfer, I will keep that in mind. – gusaindpk Jul 07 '17 at 10:24
  • @gusaindpk: Thanks a ton for your time. sending a txt file in such a way,sends its content but how to show it as a txt file to the receiver. sc at receiver's end : https://ibb.co/e4jm5F . how to make it as a downloadable link ? – Samuel Jul 09 '17 at 09:30