Make a simple chat room with Node (with websokcet tutorial)

Keywords: node.js JSON Vue socket npm

I've been talking about theory before. Let's talk about dry goods this time.
By the way, let's write that vue series from zero single row in a few days. Usher is Usher after all, and it is really difficult to simulate the whole vue for a while and a half.

Keep talking. (We need a node environment here, on a computer.)
If you don't install node, check how to install it.
If you don't know how to install dependency packages, check it too.
If you don't know how to run the js file, check it too.

I'll use a toolkit called nodejs-webscoket directly.

1. First, create a web socket service, which takes up 3000 ports:

const ws = require('nodejs-websocket');

const wsServer = ws.createServer(function(res) {
    console.log('There's a new connection');
    setTimeout(function(){res.sendText('hello')}, 1000);
})

wsServer.listen(3000, function(err){if(!err) console.log('created successfully');};

Then start the service, remember to start before starting the service
npm install  nodejs-websocket --save
 Otherwise, missing dependency packages will be reported

At this point you can enter it in the console console of the browser

var connect1 = new WebSocket('ws://localhost: 3000');
var connect2 = new WebSocket('ws://localhost: 3000');

See that the node console prints three lines
Create success, have a new connection, have a new connection

This is where the ws service was created successfully.

2. Then there is the front-end and back-end interaction.

There's a sentence just behind the scenes.

setTimeout(function(){res.sendText('hello')}, 1000);

This is a part of the back-end transmission to the front-end, but because the front-end does not write acceptance methods.

So you can rewrite a connect3 test to test the front-end and back-end interaction.

    var connect3 = new WebSocket('ws://localhost: 3000');
    connect3.onmessage = function(res) {
        console.log(res);
    }

If it's all right, a message comes out of the browser console a second later.

Just said the background to the front end of the message, and then say the front end to the back end of the message;
The method of sending messages from the front end to the back end is called send.
The nodejs-websocket acceptance method is called on('text')
Here, rewrite the background and add some functions to it.

const ws = require('nodejs-websocket');

const wsServer = ws.createServer(function(res) {
    console.log('There is a new connection');
    res.on('text', function(text) {
        console.log(text);
        res.sendText('I got your message.' + text)
    })
})

wsServer.listen(3000, function(err){if(!err) console.log('Create Success');});

Then restart the ws server... just run the js again

The front-end browser console also rewrites press Enter (just restarted in the background, which is equivalent to re-adjusting the interface).

    var connect = new WebSocket('ws://localhost: 3000');
    connect.onmessage = function(res) {
        console.log(res);
    }

After successful connection
Enter a sentence from the browser console

  connect.send('1234556')

At this point, you can see that the background has returned a message to this side... so that the basic long connection function is completed.

Then you give each connection its own name.

On the front end side, each connection has a name, such as connect, connect 1, connect 2. But there is no clear distinction between the background.
So when the front-end links to websocket, bring in the information, add a URL package to the back-end, parse the url, there are not many rooms, just a chatRoom, and fix the parameter as name. (Lazy to write judgments)
Rewrite the background

const ws = require('nodejs-websocket');
const url = require('url');
const wsRooms = {chatRoom:{}};// Used for accepting rooms

const wsServer = ws.createServer(function(conn) {
    var urlInfo = url.parse(conn.path, true);
    wsRooms.chatRoom[urlInfo.query.name] = conn; // Name this res
    console.log('There is a new connection');
    console.log(wsRooms);
})

wsServer.listen(3000, function(err){if(!err) console.log('Create Success');});

This is when the front-end browser enters

var connect = new WebSocket('ws://localhost:3000/chatRoom?name=hello');
    connect.onmessage = function(res) {
        console.log(res);
    }
    

Background wsRooms has added this dialog connection to its chatRoom. And it's called hello.

And then it's the last step, chat.
As soon as there was an experiment, the front end send and the back end returned a'I got your message'.
Now it's going to be the front end send, the back end find the send person, and then send the send message to that person.

Because each conversation has been named above, send a user, send a text, and send the user in the back end after parsing. I'll go straight to the code.

const ws = require('nodejs-websocket');
const url = require('url');
const wsRooms = {chatRoom:{}};// Used for accepting rooms

const wsServer = ws.createServer(function(res) {
    var urlInfo = url.parse(res.path, true);
    wsRooms.chatRoom[urlInfo.query.name] = res; // Name this res
    console.log('There is a new connection');
    console.log(wsRooms);
    res.on('text', function(res) {
        var data = JSON.parse(res);
        var sender = data.name;
        var text = data.text;
        var message = {name: urlInfo.query.name, text: text};
        wsRooms.chatRoom[sender].sendText(JSON.stringify(message));
    })
})

wsServer.listen(3000, function(err){if(!err) console.log('Create Success');});

Then the browser console

    var hello = new WebSocket('ws://localhost:3000/chatRoom?name=hello');
    hello.onmessage = function(res) {
        console.log(res);
    }
    
    var lolo = new WebSocket('ws://localhost:3000/chatRoom?name=lolo');
    lolo.onmessage = function(res) {
        console.log(res);
    }
    
    //After the link succeeds, enter
    hello.send(JSON.stringify({name:'lolo', text: 'hello  lolo'}));
To better test the effect, two consoles can be opened, one to send messages, and the other to jump out of the message, which is equivalent to the chat push.

Posted by justindublin on Sun, 21 Jul 2019 01:24:12 -0700