Why use websocketWebsocket is a network communication protocol, generally used for real-time communication. The websocket protocol is similar to the http protocol. The http protocol has a flaw in that it can only be initiated by the client side, and the server side returns the corresponding result based on the request URL and the parameters passed. Websocket is Websocket is applicable to scenarios such as web chat rooms, web customer service, and instant messaging scenarios where the front-end and back-end frequently exchange data. Socket.io A bidirectional and low-latency websocket communication package with high performance, high reliability and scalability. Socket.IO is a library that enables real-time, bidirectional, event-based communication between browsers and servers. It includes:
Official website Open Source ProjectsThe following code and time items will be published in the open source project [nodejs-study], welcome to download and study Effect Preview After entering Front-end page: a chat UI box, including sending and receiving functions http://localhost:3000/test Background websocket: listening and replying app.jsFirst you need to install the express and socket.io libraries Type Type Next, we will monitor the two paths
const express = require('express'); const app = express(); const http = require('http'); const server = http.createServer(app); const { Server } = require("socket.io"); const io = new Server(server); app.get('/', (req, res) => { res.send('<h1>Hello world</h1>'); }); app.get('/test', (req, res) => { res.sendFile(__dirname + '/index.html'); }); // io.on('connection', (socket) => { // console.log('a user connected'); // }); //by zhengkai.blog.csdn.net //Process socket.on information and socket.emit reply information //Here, capitalize the received msg io.on('connection', (socket) => { //Socket.io by zhengkai.blog.csdn.net socket.on('chat message', (msg) => { console.log('received: ' + msg); socket.emit("chat message", msg.toUpperCase()); }); }); //Listen on port 3000 server.listen(3000, () => { console.log('listening on *:3000'); }); index.htmlThis does some styling, and has the following body content:
As for the script part, first use the official socket.io js client to initialize a connection and add a listening event:
<!DOCTYPE html> <html> <head> <title>Socket.IO chat</title> <style> body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; } #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); } #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; } #input:focus { outline: none; } #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages > li { padding: 0.5rem 1rem; } #messages > li:nth-child(odd) { background: #efefef; } </style> </head> <body> <ul id="messages"></ul> <form id="form" action=""> <input id="input" autocomplete="off" /><button>Send</button> </form> </body> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); var messages = document.getElementById('messages'); var form = document.getElementById('form'); var input = document.getElementById('input'); //Output to screen function addMessage(str){ const li = document.createElement("li") li.innerHTML=str; messages.appendChild(li); } // console.log(form) form.addEventListener('submit', function(e) { e.preventDefault(); if (input.value) { //Socket.io by zhengkai.blog.csdn.net let msg = 'Send message:' + input.value; console.log(msg) socket.emit('chat message', input.value); addMessage(msg); //Clear an input box//input.value = ''; } }); socket.on("chat message", (arg) => { let msg = 'Receive message:' + arg; console.log(msg); // world addMessage(msg); }); </script> </html> This is the end of this article about nodejs combined with Socket.IO to implement websocket instant messaging. For more related node websocket instant messaging content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: N ways to cleverly implement adaptive dividers with CSS
>>: Web Design Tips: Simple Rules for Page Layout
Preface I recently used a virtual machine to inst...
Here is a single-line layout using ul>li for l...
Table of contents Introduction to Arrays Array li...
These introduced HTML tags do not necessarily ful...
1. Environment: CentOS7, Openssl1.1.1k. 2. Concep...
1. Enter the /etc/init.d directory: cd /etc/init....
Table of contents 1. Related binlog configuration...
Table of contents 1. Parent component passes valu...
Occasionally you'll see characters such as ...
This article example shares the specific code of ...
This article provides some commonly used rewrite ...
Enter net start mysql in cmd and the prompt is: T...
There are two ways to export csv in win10. The fi...
I recently joined a new company and found some mi...
This article shares the specific code for WeChat ...