2014-01-17 43 views
0

我有一个简单的客户端服务器Web应用程序,它使用Web套接字发送/接收信息。客户端可以正确地连接和接收配置文件,但是当我尝试使用“socket.emit('message',{my:'data'})”从客户端发送“测试”消息时;“它不显示。在服务器上我没有检查使用Wireshark,数据包将在服务器到达socket.io未收到数据

var sIoPort = 8181; 
var host = '192.168.4.111'; 
var fs = require('fs'); 

var iniMsg = fs.readFileSync('data.json','utf8'); 

var http = require("http").createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(index); 
}); 
http.listen(sIoPort,host); 

var browserServer = require('socket.io').listen(http); 
browserServer.on('connection', function (socket) { 
    console.log('Client websocket connected'); 

    // send the config file if available 
    browserServer.sockets.emit('msg',iniMsg.toString()); 
}); 

browserServer.on('message', function (message) { 
    console.log('received message: ' + message); 
}); 

客户端

/////////////////////////////////////////////////////////////////////////////// 
socket = io.connect("192.168.4.111",{"port":8181}); 
socket.on('connect',function() {if(DEBUG) console.log('Socket Connected');}); 
socket.emit('message', {my: 'data'}); // test if server receives message 
socket.on('msg',function(data) { 
    var json = JSON.parse(data); 

    // add the maps to the the GUI 
    switch(json.type) { 
     case 'maps': add_maps_from_json(json, null); 
        break; 
    } 
}); 

socket.on('disconnect',function() {if(DEBUG) console.log('Socket Disconnected');}); 
///////////////////////////////////////////////////////////////////////////////// 
+0

你的客户端代码看起来像? – max

+0

添加客户端 – tony590

回答

1

修改服务器端侦听器,它关注的插座上的事件。

browserServer.on('connection', function (socket) { 
    console.log('Client websocket connected'); 

    // send the config file if available 
    browserServer.sockets.emit('msg',iniMsg.toString()); 

    socket.on('message', function (message) { 
    console.log('received message: ' + message); 
    }); 

}); 
+0

Thx队友,我怎么能这样愚蠢的错误。谢谢 – tony590