node.js socket.io simple chat

2019-01-17 18:01发布

I'm starting playing with node.js and as everybody, I want do a chat.

My idea is run node.js with socket.io in the port 9090, for example, and my client html in the port 8080. My html client will be served independent.

My server:

var sys = require('sys');
var express = require('express');
var io = require('socket.io');

var app = express.createServer();

app.listen(8080);

var socket = io.listen(app);

socket.on('connection', function (client) {
    client.on('message', function (msg) {
        socket.broadcast(msg);
    });
    client.on('disconnect', function () {
    });
});

My client:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script src="http://cdn.socket.io/stable/socket.io.js"></script>
        <script>
            $(document).ready(function () {
                var socket = new io.Socket("localhost", {port: 8080});

                socket.on('connect', function () {
                    socket.send('A client connected.');
                });
                socket.on('message', function (message) {
                    $('div#messages').append($('<p>'), message);
                });
                socket.on('disconnect', function () {
                    console.log('disconnected');
                });
                socket.connect();

                $('input').keydown(function (event) {
                    if(event.keyCode === 13) {
                        socket.send($('input').val());
                        $('input').val('');
                    }
                });
            });
        </script>
    </head>
    <body>
        <input type="text" style="width: 300px;" />
        <div id="messages" style="border:solid 1px #000;">&nbsp;</div>
    </body>
</html>

I'm running in ubuntu 11.04 with node.js v0.4.10.

The server works fine, but the client can't do connection, in the console.log on google Chrome I received this message: XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1311465961485. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

The server.js is in a folder in /var/www/cliente/chat/public.

What's the problem?

3条回答
神经病院院长
2楼-- · 2019-01-17 18:46

When I updated my client to:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script src="http://localhost:8080/socket.io/socket.io.js"></script>
        <script>
                var socket = io.connect("http://localhost", {port: 8080});

        socket.on('connect', function () {
                    socket.send('A client connected.');
                });

                socket.on('message', function (msg) {
                    $('div#messages').append($('<p>'), msg);
                });

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

        $(document).ready(function(){
                $('#btn_send').click(function (event) {
                    socket.send($('#txt_msg').val());
                    $('#txt_msg').val('');
            });
                });
        </script>
    </head>
    <body>
        <input type="text" id="txt_msg" style="width: 300px;" /><input type="button" id="btn_send" value="send" />  
        <div id="messages" style="border:solid 1px #000;">&nbsp;</div>
    </body>
</html>

Everything worked.

I was using a version 0.7 of the socket.io that was the problem: https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7

查看更多
ら.Afraid
3楼-- · 2019-01-17 18:52

You cannot make AJAX requests to URLs that are not on the same hostname and port as the current page. It's a security restriction in all web browsers.

查看更多
孤傲高冷的网名
4楼-- · 2019-01-17 19:00

Your client code is not actually being served from port 8080 as you want.

var sys = require('sys');
var express = require('express');
var io = require('socket.io');

var app = express.createServer();
app.listen(8080);
app.use(express.static(__dirname));

app.get('/', function(req, res){
    res.render('index.html', { title: 'Chat' });
});

var socket = io.listen(app);

socket.on('connection', function (client) {
    client.on('message', function (msg) {
        socket.broadcast(msg);
    });
    client.on('disconnect', function () {
    });
});

This should fix your Access-Control-Allow-Origin errors. Execute node server.js and connect to http://localhost:8080. A couple additional notes:

  1. Make sure you have installed socket.io 0.6.x since that's what you are including in your html file. 0.7.x is backwards incompatible.

  2. With this configuration you'll be running socket.io on the same port you are serving your page from (as opposed to 9090).

查看更多
登录 后发表回答