【问题标题】:Connecting Node.JS and Socket.IO external连接 Node.JS 和 Socket.IO 外部
【发布时间】:2014-11-01 15:25:24
【问题描述】:

我一直在使用 NodeJS 和 socket.io 来实现推送 api 和 filewatcher。

我看过这个例子: http://www.gianlucaguarini.com/blog/nodejs-and-a-simple-push-notification-server/

我启动并运行了服务器,当 XML 更改时,服务器将推送通知。 如果我转到 localhost:8000,我只会看到数据更改。如果我只是打开文件 node.html 它将保持空白并给出错误(在调试中)socket.io 无法找到(404)。

我做错了什么还是需要添加到代码中?

这是代码(server.js):

    var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    parser = new require('xml2json'),
    fs = require('fs');

// creating the server ( localhost:8000 )
app.listen(8000);

// on server started we can load our client.html page
function handler(req, res) {
    fs.readFile(__dirname + '/node.html', function(err, data) {
        if (err) {
            console.log(err);
            res.writeHead(500);
            return res.end('Error loading node.html');
        }
        res.writeHead(200);
        res.end(data);
    });
}

// File watcher
io.sockets.on('connection', function(socket) {
    console.log(__dirname);
    // watching the xml file
    fs.watch(__dirname + '/cache/file.xml', function(curr, prev) {
        // on file change we can read the new xml
        fs.readFile(__dirname + '/cache/file.xml', function(err, data) {
            if (err) throw err;
            // parsing the new xml data and converting them into json file
            var json = parser.toJson(data);
            // adding the time of the last update
            json.time = new Date();
            // send the new data to the client
            socket.volatile.emit('file', json);
        });
    });
});

node.html

<html>
    <head>
    <!-- 
     * Author:      Gianluca Guarini
     * Contact:     gianluca.guarini@gmail.com
     * Website:     http://www.gianlucaguarini.com/
     * Twitter:     @gianlucaguarini
    -->
        <title>Push notification server</title>
    </head>
    <body>
        <div id="file"></div>
    <script src="socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    // creating a new websocket
    var socket = io.connect('192.168.1.11:8000/');

    // on every message recived we print the new datas inside the #container div
    socket.on('file', function (data) {
        // convert the json string into a valid javascript object
        var data = JSON.parse(data);
        $('#file').html(data);
    });


    </script>
    </body>
</html>

【问题讨论】:

    标签: node.js socket.io push


    【解决方案1】:
    var socket = io.connect('http://192.168.2.103:3000/');
    // btw. var socket = io.connect('http://localhost:3000/');
    
    
    
    socket.on('int', function(sender,passwort, x,y,z,xr,yr,zr){
    
                //es werden nur Parameter von sender name mit dem passwort pw   
                //akzeptiert!
    
                if( sender == "name" & passwort == "pw"){
                zwSchrauberX = x;
                zwSchrauberY = y;
                zwSchrauberZ = z;
                zwSchrauberXr = (xr%360)*2*pi/360;
                zwSchrauberYr = (yr%360)*2*pi/360;
                zwSchrauberZr = (zr%360)*2*pi/360;
                //console.log(zwSchrauberX);
                //console.log(zwSchrauberY);
                //console.log(zwSchrauberZ);                
                document.getElementsByTagName('p')[2].innerHTML ="Nachricht von:"+sender + "<br>" + " x:" +x+ " y:" +y+" z:"+z + "<br>" + ' xr:' +(xr%360)+'; yr:' +(yr%360)+'; zr:'+(zr%360)+ "<br>" +" Zeit:"+ new Date().getTime();
    
                }
            });
    

    //服务器:index.js

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var xl = 0;
    var yl = 0;
    var zl= 0;
    
    app.get('/', function(req, res){
      res.sendFile(__dirname + '/index.html');
    });
    
    
    
    io.on('connection', function(socket){
      socket.on('chat message', function(msg){
        io.emit('chat message', msg);
      });
    
     socket.on('int2', function(x,y,z){
        io.emit('int', x,y,z);
      });
    
     socket.on('int', function(sender,passwort, x,y,z,xr,yr,zr){
        io.emit('int', sender,passwort, parseFloat(x),parseFloat(y),parseFloat(z),parseFloat(xr),parseFloat(yr),parseFloat(zr));
      });
    
     socket.on('val', function(){
            io.emit('int', xl,yl,zl);
      }); 
    
    });
    
    http.listen(3000, function(){
      console.log('listening on *:3000');
    });
    
    The index.html
    
    
    <html>
      <head>
        <title>Socket.IO chat</title>
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { font: 13px Helvetica, Arial; }
          form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
          form input { border: 0; padding: 10px; width: 10%; margin-right: .5%; }
          form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
    
          form2 { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
          form2 input { border: 0; padding: 10px; width: 10%; margin-right: .5%; }
          form2 button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
          #messages { list-style-type: none; margin: 0; padding: 0; }
          #messages li { padding: 5px 10px; }
          #messages li:nth-child(odd) { background: #eee; }
        </style>
    
      </head>
      <body>
        <ul id="messages"></ul>
        <form action="">
          <input id="x" autocomplete="off", onkeyup="this.value=this.value.replace(/\D/, '');"/>
          <input id="y" autocomplete="off", onkeyup="this.value=this.value.replace(/\D/, '');" />
          <input id="z" autocomplete="off", onkeyup="this.value=this.value.replace(/\D/, '');"/>
          <input id="xr" autocomplete="off", onkeyup="this.value=this.value.replace(/\D/, '');" />
          <input id="yr" autocomplete="off", onkeyup="this.value=this.value.replace(/\D/, '');" />
          <input id="zr" autocomplete="off", onkeyup="this.value=this.value.replace(/\D/, '');"/>
          <button>Send</button>
          <button id="n1">TestSend</button>
        </form>
    
    
    
         <form action="">
    
        </form>
    
    
    
        <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
        <script>
    
    
          var socket = io();
          var username ='';
          var passwort ='';
          var count = 0;
          var array_x = new Array(0);
          var array_y = new Array(0);
          var array_z = new Array(0);
    
    
    
            $('#x').val('0');
            $('#y').val('0');
            $('#z').val('0');
            $('#xr').val('0');
            $('#yr').val('0');
            $('#zr').val('0');
    
            username = prompt('Your name:', username)|| '';
    
            passwort = prompt('Passwort:', passwort)|| '';
    
          $('n1').submit(function(){
            //socket.emit('chat message', username+ ': '+ $('#x').val());
            socket.emit('val');
    
            return false;
          });   
    
          $('form').submit(function(){
            //socket.emit('chat message', username+ ': '+ $('#x').val());
            socket.emit('int', username,passwort, $('#x').val(), $('#y').val(), $('#z').val(),$('#xr').val(), $('#yr').val(), $('#zr').val());
    
            return false;
          });
    
    
        socket.on('int', function(sender,passwort, x,y,z,xr,yr,zr){
        $('#messages').append($('<li>').text('Gesendet von:'+sender+ ' x:' +x+'+ y:' +y+' z:'+z + ' xr:' +xr+'; yr:' +yr+'; zr:'+zr));
    
        $('#x').val(x);
        $('#y').val(y);
        $('#z').val(z);
        $('#xr').val(xr);
        $('#yr').val(yr);
        $('#zr').val(zr);
    
        array_x[count] = parseFloat(x);
        array_y[count] = parseFloat(y);
        array_z[count] = parseFloat(z);
        count++;
        console.log(array_x);
        console.log(array_y);
        console.log(array_z);
      });
    
    </script>
    

    更多源码:
    http://socket.io/
    https://github.com/rauchg/chat-example

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 1970-01-01
      • 2011-06-30
      • 2018-05-14
      • 2015-05-04
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      相关资源
      最近更新 更多