Socket.IO basic example not working

2019-01-28 22:29发布

问题:

I'm 100% new to Socket.IO and have just installed it. I was trying to follow some examples, and can get the server side running but I can't seem to get the client side connected.

The following is my server.js:

var http = require('http'), io = require('socket.io'),

server = http.createServer(function(req, res){ 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end('<h1>Hello world</h1>'); 
});
server.listen(8090);

var socket = io.listen(server); 
socket.on('connection', function(client){ 

    console.log('Client connected.');

    client.on('message', function(){ 
        console.log('Message.');
        client.send('Lorem ipsum dolor sit amet');
    });

    client.on('disconnect', function(){
        console.log('Disconnected.');
    });

});

This is my index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Socket Example</title>
    <base href="/" />
    <meta charset="UTF-8" />
    <script src="http://localhost:8090/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
</head><body>
<script type="text/javascript"> 
$(document).ready(function(){

    var socket = new io.Socket('localhost', { 'port': 8090 });

    socket.connect();
    console.log("Connecting.");

    socket.on('connect', function () {
        console.log("Connected.");
    });

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

    socket.on('disconnect', function () {
        console.log("Disconnected.");
    });

});
</script> 
</body></html>

When I do node server.js it indicates that socket.io is started.

When I load the index.html a line comes up indicating "debug - served static /socket.io.js" But nothing else, no console messages or other lines.

Any guidance you could provide would be very much appreciated. As I said I'm 100% green with this so if you could break it down as much as possible I'd also appreciate it.

Thanks

回答1:

In same origin policy, localhost:8090 and localhost are not the same origin (different port), so localhost/index.html cannot connect to socket.io on localhost:8090.

One option is to make index.html on localhost:8090 (see code below). Then you just put "index.html" into the same directory of your server script, start the server and type localhost:8090 in your browser.

var fs = require('fs');

server = http.createServer(function(req, res){
    fs.readFile(__dirname + '/index.html', 'utf-8', function(err, data) { // read index.html in local file system
        if (err) {
            res.writeHead(404, {'Content-Type': 'text/html'});
            res.end('<h1>Page Not Found</h1>');
        } else { 
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        }
    });
});