在Node.js程序中,可以借助 Socket.IO来构建实时应用。 然而有时候后台与Socket.IO是异构的,比如Java、Python的Web后台。 这时可以利用 Redis的订阅/发布机制作为中转,连接异构的后台和Socket.IO服务。 本文介绍如何在Socket.IO中订阅Redis Channel。
至于如何在Java/Python/C#中发布消息到Redis Channel,请参照对应语言的Redis SDK。
安装软件
- Redis。可以参照官网 http://redis.io/来安装,在 这里可以下载。
- Node.js。也可以在官网 https://nodejs.org/直接下载。
然后创建一个文件夹作为Socket.IO服务器项目,在其中安装 Socket.IO和Node.js的 redis客户端。
npm install Socket.IO redis --save
简单的Socket.IO服务
创建 app.js文件,写一个基于Node.js HTTP模块的Socket.IO服务器。 我们创建两个命名空间,一个 notification,一个 chatting。
var server = require('http').createServer();var io = require('Socket.IO')(server);io .of('/notification') .on('connection', socket => { console.log('user connected to notification'); socket.on('disconnect', () => console.log('user disconnected')); });io .of('/chatting') .on('connection', socket => console.log('user connected to message'));server.listen(3001, () => console.log('Socket.IO listen to port 3001'));
不同的浏览器端可以连接到不同的命名空间,例如连接到 notificaiton:
var socket = io('/notification');socket.on('message', function (msg) { console.log(msg);});
需要在HTML中引入 ,见 http://Socket.IO/download/。更多Socket.IO的例子,请参考: http://Socket.IO/docs/#how-to-use
订阅Redis Channel
在上述服务器文件中引入 redis并创建一个客户端,可以收到所有频道的信息。 可以通过 switch-case来分发各频道的消息。
var redis = require('redis');var redisClient = redis.createClient();var NOTIFICATION_CHANNEL = 'notification_channel', CHATTING_CHANNEL = 'chatting_channel';redisClient.on('message', function(channel, message) { switch (channle){ case NOTIFICATION_CHANNEL: console.log('notification received:', message); io.of('/notification').emit('message', message); break; case CHATTING_CHANNEL: console.log('chatting received:', message); io.of('/chatting').emit('message', message); break; }});redisClient.subscribe(NOTIFICATION_CHANNEL);redisClient.subscribe(CHATTING_CHANNEL);
在 redis.createClient()的参数中可以设置Redis服务器的主机名、端口、密码等信息, 参见对应的 文档。
测试执行
启动Socket.IO服务器:
$ node app.jsSocket.IO listen to port 3001
在命令行(Bash、Zsh…)中打开 redis-cli,并发布一条消息:
$ redis-cli127.0.0.1:6379> publish notification "fuck you!"
然后Socket.IO便会输出 notification received: fuck you!,同时所有连接到 /message命名空间的浏览器端也会收到消息并输出到控制台。

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
