“This is the 10th day of my participation in the First Challenge 2022. For details: First Challenge 2022”
preface
Nodejs + WebSocket in the “Nodejs + WebSocket simple introduction and examples – Chapter 1” in a simple introduction, Nodejs + WebSocket use methods and functions, today to use it to build a simple chat room function.
Nodejs+WebSocket create background server function 2. Vue view layer, receive background data and render page 3. LocalStorage stores user information such as session ID
Vue + Webpack generates vUE projects
Scaffolding projects are also very easy to use, simple command can be done
# vue init webpack web-im
Copy the code
Then work your way down and fill in the project name, description, author, and so on to complete the installation.
Modules can now be automatically installed. Of course, you can go to the directory and execute NPM install
# cd web-im
# npm install
Copy the code
This is the generated project structure.
The WebSocket server
Create a server/index.js file in the root directory of the project.
var ws = require("nodejs-websocket");
// Moment is used here
var moment = require('moment');
console.log("Start establishing connections...")
let users = [];
// Broadcast to all connected clients
function boardcast(obj) {
server.connections.forEach(function(conn) {
conn.sendText(JSON.stringify(obj)); })}function getDate(){
return moment().format('YYYY-MM-DD HH:mm:ss')}var server = ws.createServer(function(conn){
conn.on("text".function (obj) {
obj = JSON.parse(obj);
if(obj.type===1){
users.push({
nickname: obj.nickname,
uid: obj.uid
});
boardcast({
type: 1.date: getDate(),
msg: obj.nickname+'Join the chat room'.users: users,
uid: obj.uid,
nickname: obj.nickname
});
} else {
boardcast({
type: 2.date: getDate(),
msg: obj.msg,
uid: obj.uid,
nickname: obj.nickname
});
}
})
conn.on("close".function (code, reason) {
console.log("Close connection")}); conn.on("error".function (code, reason) {
console.log("Abnormal shutdown")}); }).listen(8001)
console.log("WebSocket setup completed")
Copy the code
This is basically the same structure as Nodejs + WebSocket Introduction and Examples – Chapter 1, except that there is one method used to send messages to the client
server.connections.forEach(function(conn) {
conn.sendText(JSON.stringify(obj));
})
Copy the code
Traverse all connections, send messages.
Why convert json.stringify (obj) to string?
The sendText method can only pass in strings, so we need to convert our object.
Conn.on (“text”, ()=>{}) checks a type passed in from the client.
WebSocket Client view layer
<div id="app">
<c-dialog
ref="loginDialog"
title='Please enter your nickname'
confirmBtn="Start chatting"
@confirm="login"
>
<input class="nickname" v-model="nickname" type="text" placeholder="Please enter your nickname">
</c-dialog>
<div class="web-im">
<div class="header im-title">The chat room</div>
<div class="content im-record">
<div class="li" :class="{user: item.uid == uid}" v-for="item in messageList">
<template v-if="item.type===1">
<p class="join-tips">{{item.msg}}</p>
</template>
<template v-else>
<div class="img">{{item.nickname}}</div>
<p class="message-box">{{item.msg}}</p>
</template>
</div>
</div>
<div class="footer im-input">
<input type="text" v-model="msg" placeholder="Please enter the content">
<button @click="send">send</button>
</div>
</div>
</div>
Copy the code
Style aspects do not explain, are very simple style, interested can click the bottom to obtain the source view.
WebSocket client
export default{...data(){
return {
uid: ' '.nickname: ' '.socket: ' '.msg: ' '.messageList: []}},mounted() {
let vm = this;
let user = localStorage.getItem('WEB_IM_USER');
user = user && JSON.parse(user) || {};
vm.uid = user.uid;
vm.nickname = user.nickname;
if(! vm.uid){ vm.$refs.loginDialog.show() }else {
vm.conWebSocket();
}
document.onkeydown = function (event) {
var e = event || window.event;
if (e && e.keyCode == 13) { // The enter key has a value of 13
vm.send()
}
}
},
methods: {
send(){
if(!this.msg){
return
}
this.sendMessage(2.this.msg)
},
sendMessage(type, msg){
this.socket.send(JSON.stringify({
uid: this.uid,
type: type,
nickname: this.nickname,
msg: msg
}));
this.msg = ' ';
},
conWebSocket(){
let vm = this;
if(window.WebSocket){
vm.socket = new WebSocket('ws://localhost:8001');
let socket = vm.socket;
socket.onopen = function(e){
console.log("Server connection successful");
if(! vm.uid){// Generate a new user ID and store it in localStorage
vm.uid = 'web_im_' + moment().valueOf();
localStorage.setItem('WEB_IM_USER'.JSON.stringify({
uid: vm.uid,
nickname: vm.nickname
}))
vm.sendMessage(1)
}
}
socket.onclose = function(e){
console.log("Server down");
}
socket.onerror = function(){
console.log("Connection error");
}
// Receive a message from the server
socket.onmessage = function(e){
let message = JSON.parse(e.data); vm.messageList.push(message); }}},login(){
this.$refs.loginDialog.hide()
this.conWebSocket(); }}}Copy the code
Localstorage. getItem(‘WEB_IM_USER’) : if localstorage. getItem(‘WEB_IM_USER’) : if localstorage. getItem(‘WEB_IM_USER’) : if localstorage. getItem(‘WEB_IM_USER’) : if localstorage. getItem Onmessage listens to the message sent by the server, converts it into JSON, pushes it into the messageList array, and then rendering it to the page. 4. Check whether the message is sent by the user. If the message content is displayed on the right, messages sent by other users are displayed on the left, and set different background colors
Here we have a simple Node + Websocket group chat, what did you learn from it?
Finally, let’s take a look
conclusion
Nodejs + WebSocket group chat functionality and core This is the core code:
function boardcast(obj) {
server.connections.forEach(function(conn) {
conn.sendText(JSON.stringify(obj)); })}Copy the code
Send a message to all connectors so that all of them can receive the message.
Source address: source address