在openshift Nodejs中,Socket.io响应200 Ok,但是console.log值不可见。我的套接字正在工作?

时间:2016-03-02 14:49:24

标签: node.js socket.io openshift

创建了index.js(服务器)

var express = require('express');
var app = express();

///creating server
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { origins:'http://nodejs-atnodejs.rhcloud.com:8000' });

下面是剩下的代码  路由到index.html页面

app.get('/', function (req, res) {
    console.log('in socket---' + res);
    res.sendfile('index.html');
});
///socket connection
io.sockets.on('connection', function (socket) {
    socket.on('chatmessage', function (msg) {
        io.emit('chatmessage', msg);
        console.log('in socket---' + data);
    });
});
/// Listen to Openshift port
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);

    创建了index.html(客户端)

src="http://nodejs-atnodejs.rhcloud.com:8000/socket.io/socket.io.js   
     var socket = io.connect('http://nodejs-atnodejs.rhcloud.com:8000');
       console.log('this is index page');
        socket.on('chatmessage', function (data) {
            console.log('chatmessage---' + data);
            socket.emit('chatmessage', { my: 'data' });
        });     

    从浏览器访问时: when accessed from browser

Problem is not getting "console.log('chatmessage---' + data);" which is inside the socket.. 

and keep on getting xhr-polling../t=xxxxx responses..

is my socket working properly? 

1 个答案:

答案 0 :(得分:1)

您的浏览器和服务器代码都在监听' chatmessage'在连接之后,您的浏览器或服务器应首先发出事件而另一个应该正在监听,例如......

// server
io.sockets.on('connection', function (socket) {
  socket.emit('chatmessage', /*some data*/);
});

//client
socket.on('chatmessage', function (data) {
  console.log('chatmessage---' + data);
});