2

我在连接 io.on 功能时遇到问题(我真的很沮丧)。我正在使用 express、ioredis 和 socket.io。redis 工作正常,但 socket.io 不工作。它不工作。请帮助。

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();

//port connection
server.listen(3000);
console.log('server listening 3000');

//redis sub (working fine)
redis.subscribe('test-channel', function () {
    console.log('Redis: test-channel subscribed');
});

//this code is not working (stop execution)
io.on('connection', function(socket){
    console.log("new client connected");
});


io.on('connection', function (socket) {
    console.log("new client connected");

    redis.subscribe('message');
    console.log("redis start");

    //send message to frontend
    redis.on("message", function(channel, message) {
        console.log("mew message in queue "+ message + "channel");
        socket.emit(channel, message);
    });
    //close socket
    socket.on('disconnect', function() {
        redis.quit();
        console.log('redis disconnected!');
    });

});

客户端

     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>

   <script>
        var socket = io.connect('http://localhost:3000');
        socket.on('message', function (data) {
            $(".progress-bar").css('width',+data+'%');
            alert('connection established');
            $("#messages").append( "<p>"+data+"</p>" );
        });
    </script>
4

2 回答 2

1

服务器端

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server); // it was require('socket.io')(server);

server.listen(3000);

客户端

io.sockets.on('connection', function(socket){
    console.log("new client connected");
});
于 2016-07-08T12:28:28.667 回答
0

const { 服务器 } = 要求(“socket.io”) const io = 新服务器(服务器)

于 2021-09-13T07:54:11.963 回答