简体   繁体   中英

Socket.io doesn't work , Node Js

actually i'm trying to see if a client is connected or no with socket.io. but in the console nothing appears excepte that the server is working.

//server.js

var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client
var server = http.createServer(function(req, res) {
  fs.readFile('./index.html', 'utf-8', function(error, content) {
    res.writeHead(200, {"Content-Type": "text/html"});
    res.end(content);
  });
});


// Chargement de socket.io

var io = require('socket.io').listen(server);
// Quand un client se connecte, on le note dans la console
io.sockets.on('connection', function (socket) {
  console.log('Un client est connecté !');
});
server.listen(8080);

//client index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Socket.io</title>
    </head>
    <body>
        <h1>Communication avec socket.io !</h1>
        <script src="/socket.io/socket.io.js"></script>
        <script>
            var socket = io.connect('http://localhost:8080');
        </script>
    </body>
</html>

I am using express api from socket.io ,

var express = require('express') ;
var app = express() ;
var server = require('http').createServer(app) ;
var socket = require('socket.io')(server) ;

Now , you need to say server to listen the port . (the port number you client is trying to connect here is 8080 ) In server script say ,

server.listen(8080) ;

Now , install express module from terminal window manually or just put a dependency file and install

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