对不起,我的英语=(
我学习了WebSocket,但不知道如何创建连接。
我使用Laravel + Redis + Socket.io(仅服务器)
在服务器server.js上
WebSocketServer = require('ws');
let webSocketServer = new WebSocketServer.Server({
port: 3000
});
let io = require('socket.io')(webSocketServer);
let Redis = require('ioredis');
let redis = new Redis();
redis.psubscribe('channel_*');
redis.on('pmessage', function (pattern, channel, message) {
console.log('Message recieved: ' + message); // work
console.log('Channel: ' + channel); // work
msg = JSON.parse(message);
io.emit(channel + ':' + msg.event, msg.data.result); // don't work
});
在客户端上
let socket = new WebSocket("ws://127.0.0.1:3000");
socket.onopen = function() {
console.log("Connect ok."); // work
};
socket.onclose = function(event) {
if (event.wasClean) {
console.log('Connect close');
} else {
console.log('Connect close 2');
}
console.log('Code: ' + event.code + ' reason: ' + event.reason);
};
socket.onmessage = function(event) {
console.log("Get data " + event.data); // don't work
};
socket.onerror = function(error) {
console.log("Error ", error);
};
但是io.emit(...)无效。
我不想使用库window.io = require('socket.io-client');
谢谢!