简体   繁体   中英

Socket.io Chat not working on server

My chat application is working properly on local server, but when I am pushing it to the openshift server, the chat functionality is not working.

I am following this example : http://socket.io/get-started/chat/

The following is my HTML code

    <body>
        <ul id="messages"></ul>
        <form action="">
            <input id="m" autocomplete="off" /><button>Send</button>
        </form>
        <script src="https://cdn.socket.io/socket.io-1.2.0.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>
    </body>

Below is my server.js

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

    var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
    var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;

    app.get('/', function (req, res) {
        res.sendfile(__dirname + '/index.html');
    });

    io.on('connection', function (socket) {
        socket.on('chat message', function (msg) {
            io.emit('chat message', msg);
        });
    });

    http.listen(port, function () {
        console.log('listening');
    });

The same code is working fine on my local server. For now I am simply broadcasting the message including the sender too.

Where am I wrong?

$( document ).ready(function() {});

this code saved me. i forgot to enclose my scripting in jquery document ready. so the final code looks like this.

  $( document ).ready(function() {
    var socket = io();
    $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
        });
     });

Your chat client needs to connect to the websocket chat server on port 8000 for ws (or 8443 for wss). Make sure you are specifying that port number when you have it connect.

I know it´sa bit late, but the document isn´t ready and that caused the error. Try this code:

$( document ).ready(function() {
        var socket = io();
        $('form').submit(function(){
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
        });
    });

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