简体   繁体   中英

How to run Socket.IO application on my Server

I'm studying how to build a simple application of a real-time chat. I found many solutions using Socket.Io and it's working perfectly on localhost, but I have no idea how to make it work on my server. Any suggestions ?

Here is my codes.

INDEX.JS

ar app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');

app.listen();

function handler (req, res) {
    fs.readFile(__dirname + '/index.html',
    function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('error loading index.html');
        }

        res.writeHead(200);
        res.end(data)
        });
    }
io.on('connection', function (socket){
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
    });
});

HTML

<script src="/socket.io/socket.io.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
        <script>
            var socket = io();
            $('form').submit(function(){
                socket.emit('chat message', $('#m').val());
                $('#m').val('');
                return false;
            });
            socket.on('chat message', function(msg){
                $('#messages').append($('<li>').text(msg));
            });
        </script>

It's hosted here: http://stg.pixechat.com/chat/

Thanks

You're loading socketio from a CDN now, which is good. However, your script looks like this:

        var socket = io();
        $('form').submit(function(){
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
        });
        socket.on('chat message', function(msg){
            $('#messages').append($('<li>').text(msg));
        });

On the first line, I believe you need io() to be io('http://stg.pixechat.com/chat')

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