Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize websocket Instant messaging by nodejs combined with Socket.IO

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shares with you how nodejs implements websocket instant messaging with Socket.IO. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.

Why use websocket?

Websocket is a network communication protocol that is generally used for real-time communication.

The websocket protocol is similar to the http protocol. The http protocol has a flaw. Only the client can initiate a request. The server returns the corresponding result according to the request url and the parameters passed.

Websocket is two-way communication, as long as the websocket connection is established, the client can send data to the server, or the server can actively send data to the client.

Websocket application scenarios: web version chat room, web version customer service, instant messaging scenarios where data is frequently exchanged between front and back ends.

Socket.io

Bidirectional and low-latency websocket packets, high performance, high reliability, scalable.

(Simply put, encapsulating and optimizing websocket.)

Socket.IO is a library that enables real-time, bidirectional, and event-based communication between browsers and servers. It includes:

server side

client side

official website

https://socket.io/

official documentation

https://socket.io/docs/v4/

open source projects

The following code and time projects will be published in the open source project [nodejs-study], welcome to download and learn

effect preview

Enter node app to run the service and you can access it through http://localhost:3000/. If you see the output listening port 3000 and the front end showing hello world, it proves that the project started successfully.

前端页面:一个聊天的UI框,包含发送和接收功能 http://localhost:3000/test

后台websocket:监听和答复

app.js

首先需要安装express和socket.io库

输入npm install express --save或者yarn add express

输入npm install socket.io--save或者yarn add socket,io

接下来实现 对 / 和 /test 两个路径的监听

/返回hello world

/test返回html连接页面

socket.on("chat message",callback function)

表示开始监听"chat message"通道,只要前后端都是一致的通道即可。

socket.emit("chat message", msg.toUpperCase());

表示对这个"chat message"通道进行回复,我们暂时是对英文字母做大写处理并返回。

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('Hello world'); });app.get('/test', (req, res) => { res.sendFile(__dirname + '/index.html');});// io.on('connection', (socket) => {// console.log('a user connected');// });//by zhengkai.blog.csdn.net//处理socket.on信息并socket.emit回复信息//这里对接收到的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()); }); });//监听端口3000server.listen(3000, () => { console.log('listening on *:3000');});index.html

这做一些样式处理,并且有以下body内容:

message的ul,可以用来追加li信息,显示记录往来

一个form表单,用来提交要发送的信息

script部分而言,首先使用官方的socket.io 的js client , 初始化一个连接,添加监听事件:

输入非空内容提交后,发送信息给websocket后台,同事也输出在信息列表

接收到信息之后,显示在信息列表

Socket.IO chat 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; } Send var socket = io(); var messages = document.getElementById('messages'); var form = document.getElementById('form'); var input = document.getElementById('input'); //输出到屏幕 function addMessage(str){ const li = document.createElement("li") li[xss_clean]=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 = '发送消息:'+input.value ; console.log(msg) socket.emit('chat message', input.value); addMessage(msg); //清空个输入框 //input.value = ''; } }); socket.on("chat message", (arg) => { let msg = '接收消息:'+arg ; console.log(msg); // world addMessage(msg); }); 感谢各位的阅读!关于"nodejs如何结合Socket.IO实现websocket即时通讯"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report