简体   繁体   中英

Get data by socket.io in html page

I have read a lot of tutorial, and sample code to send data from a node.js class to an html page and show this data. such as link1 , link2 , link3 , link4 , link5 and some others.

I am getting some data from UDP listener and need to send it after some processing to an html page to show it. here is my code:

The udp receiver:

    var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

var http = require('http'),
    dgram = require('dgram'),
    socketio = require('socket.io'),
    fs = require('fs');

var html = fs.readFileSync(__dirname + '/html/showMap.html');

var app = http.createServer(function(req, res) {
  res.writeHead(200, {
    'Content-type': 'text/html'
  });
  res.end(html);
  io.sockets.emit('welcome', { message: 'Welcome!'});

}).listen( server_port, server_ip_address, function() {
  console.log('Listening');
});

var io = socketio.listen(app),
    socket = dgram.createSocket('udp4');

socket.on('message', function(content, rinfo) {
    console.log('got message', content, 'from', rinfo.address, rinfo.port);
    io.sockets.emit('udp message', 'content' /*content.toString()*/);
});

socket.bind(5001);

and my html page which is called 'showMap.html'

<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Get Data</title>
      <script src="/socket.io/socket.io.js"></script>
  </head>
  <body>
    <div id="results">    This text will change     </div>
    <div id="date">sample another temp text</div>
    <script>
    // client code here
    var socket = io.connect('localhost', {port: 8080});
    socket.on('udp message', function(message) {
      console.log(message)
      document.getElementById("date").innerHTML = "My new text!";​
  });
  socket.on('welcome', function(data) {
    document.getElementById("results").innerHTML = data.message;
  });
    </script>
  </body>
</html>

but by sending packet, html page has not changed. Here is my console log of running code:

Atis-MacBook-Pro:startWithNode muser$ npm start

StartWithNodejs@1.0.0 start /Volumes/Project/Project/NodeJS/startWithNode node index.js

Listening got message from 127.0.0.1 64047

What is wrong in my code?

I tested this locally. In your HTML file I made two changes and it worked.

1 - Replace io.connect('localhost', {port: 8080}); with io.connect('localhost:8080');

2 - There was a strange \​ character at the end of the document.getElementById("date").innerHTML = "My new text!"; line. I deleted that and ended up with:

<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Get Data</title>
    <script src="/socket.io/socket.io.js"></script>
  </head>
    <body>
      <div id="results">    This text will change     </div>
      <div id="date">sample another temp text</div>
    <script>
      // client code here
      var socket = io.connect('localhost:8080');
      socket.on('udp message', function(message) {
      console.log(message)
        document.getElementById("date").innerHTML = "My new text!";
      });
      socket.on('welcome', function(data) {
        document.getElementById("results").innerHTML = data.message;
      });
    </script>
  </body>
</html>

Which replaces the content of results .

in this example you will be able to get JSON data from php file and send it to all connected clients.

RunThisFileThroughNodeJs.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
var request = require("request")
var url = "http://localhost/api/index.php";
events = require('events'),
    serverEmitter = new events.EventEmitter();
app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});


io.on('connection', function(socket){


    setInterval(
        function(){

            request({
                url: url,
                json: true
            }, function (error, response, body) {

                if (!error && response.statusCode === 200) {
                    io.emit('chat message', body);
                }
            });
        },5000);




});


http.listen(port, function(){
    console.log('listening on *:' + port);
});

Don't Forget to install express , request for nodejs

Now make this file i will call it index.html so the response of my file will be here.

index.html

<!doctype html>
<html>
<head>
  <title>Prices API</title>
  <script src="http://localhost/js/socket.io.js"></script>

</head>
<body>
<div id="price_list"></div>
<script>
   var socket = io();
socket.on('chat message', function(msg){

    document.getElementById("price_list").innerHTML = JSON.stringify(msg);

    console.log(msg);
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM