[英]socket.io not emitting
So, I have this app called server and the other one called client , server providers all the data for the client to consume. 因此,我有一个名为server的应用程序,另一个名为client的应用程序,服务器提供程序供客户端使用的所有数据。 The thing is, when i try to emit from server (port 8080) and receive to client (port 80) nothing happens 问题是,当我尝试从服务器(端口8080)发出并接收到客户端(端口80)时,什么也没发生
server: app.js 服务器:app.js
var app = require ("./config/server.js");
var http = require('http').createServer(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.sockets.on('connect', function (socket) {
console.log("conectou socket.id="+socket.id);
});
When the server database insert new photo, this is called: 当服务器数据库插入新照片时,这称为:
io.emit("newPhoto");
client: app.js 客户端:app.js
var app = require('./config/server');
app.listen(80, function(){
console.log('Server client instagram_clone_v01 online');
});
var io = require('socket.io');
This is called inside a ejs code : 这在ejs代码内部称为:
const socket = io.connect('http://localhost:8080', {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('newPhoto',function(){
load_posts();
});
Edited with the Answer of Federico 用费德里科的答案编辑
I added io.origins('*:*');
我添加了io.origins('*:*');
to server, but emit isn't emitting 到服务器,但发出不发出
I don't know why you are using io.sockets.on
, I couldn't find it in the documentation. 我不知道您为什么使用io.sockets.on
,但在文档中找不到它。 I've tried to clean the code, give it a try. 我试图清除代码,尝试一下。
server.js server.js
var app = require ("./config/server.js");
var http = require('http').Server(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.on('connect', socket => {
console.log("user" + socket.request.user.id + "connected");
socket.on('disconnect', function() {
console.log('A user has disconnected');
}
io.emit("newPhoto");
});
client.js client.js
//io() works only when connecting to a socket hosted on the same url/server
// For connecting to an external socket hosted elsewhere, you would use io.connect('URL');
var socket = io();
socket.on('newPhoto',function(){
load_posts();
});
In the page where your user being redirected after login, you should include these scripts: 在登录后将用户重定向到的页面中,应包括以下脚本:
<script src="/socket.io/socket.io.js"></script>
<script src="/client.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.