node.js socket.io simple chat

前端 未结 3 798
悲&欢浪女
悲&欢浪女 2020-12-09 06:04

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

3条回答
  •  -上瘾入骨i
    2020-12-09 06:45

    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).

提交回复
热议问题