Home>Article>Web Front-end> How does node+vue implement a simple WebSocket chat function? (code example)

How does node+vue implement a simple WebSocket chat function? (code example)

青灯夜游
青灯夜游 forward
2020-11-17 17:55:25 2328browse

How does node+vue implement a simple WebSocket chat function? (code example)

Related recommendations: "node js tutorial"

I recently learned about websocket instant messaging and I feel it is very powerful. Here I used node to start a service for websocket link, and then linked it in the view of vue for communication. Without further ado, let’s go directly to the code.

First of all, I need to use node’s nodejs- websocket module

Use yarn to install

yarn add nodejs-websocket --save

Of course, you can also use npm to install

npm i nodejs-websocket --save

After the installation is completed, we start writing the server code. First, I use node has a node server locally to start the websocket service

sock.js:

let ws = require("nodejs-websocket"); console.log("开始建立链接"); ws.createServer(function (conn) { conn.on("text", function (str) { console.log("收到的信息为", str); conn.send(`${str}(机器人`) }); conn.on("close", function (code, reason) { console.log("关闭连接") }); conn.on("error", function (code, reason) { console.log("异常关闭") }) }).listen(8001); console.log("链接建立完毕");

The server mainly uses nodejs-websocket to start the service and return the values required by the front end. Here I just did a simple process, adding a 'robot' string after the acceptance value,

Then, we need to start the node service,

The path behind the command must be found correctly. I placed sock.js under the socket folder in the root directory.

Execute

yarn socket

Finally, look at our client. On the client side, I want to have an input box and then a chat box:

  

Let’s take a look at the final effect:

Related Recommendation:

2020 Summary of front-end vue interview questions (with answers)

vue tutorial recommendation: The latest 5 vue.js in 2020 Video tutorial selection

For more programming-related knowledge, please visit:Programming Teaching! !

The above is the detailed content of How does node+vue implement a simple WebSocket chat function? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete