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.

6
  • 1
    may be this can be usefull stackoverflow.com/questions/18571001/… and jsfiddle.net/f8Hee/1 Commented Jul 6, 2017 at 4:18
  • @gusaindpk: Thanks but my question is for websocket. how to send files via it. Any help here ? Commented Jul 6, 2017 at 5:56
  • May be this will help you out.. stackoverflow.com/questions/11080112/… Commented Jul 6, 2017 at 9:27
  • @gusaindpk : please check the update Commented Jul 6, 2017 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, I use this with a python server (take a look at the other files). Commented Jul 6, 2017 at 18:53

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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 :-).
Thanks for your edit @halfer, I will keep that in mind.
@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 : ibb.co/e4jm5F . how to make it as a downloadable link ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.