我正在尝试连接到socket。但我没有在控制台上获得socketid。这是连接到套接字的正确方法吗?任何人都可以建议我......
我的代码:
var app = express();
var dir = process.cwd();
app.use(express.static(dir)); //app public directory
app.use(express.static(__dirname)); //module directory
var server =require('http').createServer(app);
var io = require('socket.io')(server);
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
客户代码:
var socket = io('http://localhost:8085/socket_issue');
socket.on('connect', function(){ console.log('connected to socket'); });
socket.on('error', function(e){ console.log('error' + e); });
socket.on( 'news', function( data ){
console.log(data);
});
socket.on('disconnect', function(){});
答案 0 :(得分:0)
您的后端代码中似乎没有server.listen()
。
我编辑了服务器代码并且它正常运行:
var app = require('express')();
var dir = process.cwd();
var server =require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
不要忘记更改前端的端口,它将按预期工作:
Socket connected :Y7zi7dLRxqBA5nakAAAA