因此,我有一个名为 server 的应用,另一个是 client 的应用,服务器为服务器提供了供客户端使用的所有数据。问题是,当我尝试从服务器(端口8080)发出并且接收到客户端(端口80)时,什么都没有发生
服务器: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);
});
当服务器数据库插入新照片时,这称为:
io.emit("newPhoto");
客户端:app.js
var app = require('./config/server');
app.listen(80, function(){
console.log('Server client instagram_clone_v01 online');
});
var io = require('socket.io');
这在 ejs代码中被称为:
const socket = io.connect('http://localhost:8080', {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('newPhoto',function(){
load_posts();
});
编辑,答案为 Federico
我向服务器添加了io.origins('*:*');
,但不发光
答案 0 :(得分:0)
我不知道您为什么使用io.sockets.on
,在文档中找不到它。我已经尝试清除代码,尝试一下。
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
//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();
});
在登录后将用户重定向到的页面中,应包括以下脚本:
<script src="/socket.io/socket.io.js"></script>
<script src="/client.js"></script>