socket.io and node js: chat does not display on screen

可紊 提交于 2019-12-12 03:24:02

问题


I was giving a try to socket.io by creating a live chat, and the page refreshes itself when the message is submitted, here is the markup and the client side JS (index.html):

<body>
    <h1>Open chat</h1>

    <form id="send_message">
        <div class="chat">

        </div>
        <hr />
        <input size="28" type="text" id="message" />
        <input type="submit" value="send" />
    </form>

    <script src="http://code.jquery.com/jquery-latest-min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        JQuery(function($){
            var socket = io.connect();
            var $message_form = $('#send_message');
            var $message_box = $('#message');
            var $chat = $('#chat');

            $message_form.submit(function(e){
                e.preventDefault();
                socket.emit('send message', $message_box.val());
                $message_box.val('');                   
            })
        });

        socket.on('new message', function(data){
            $chat.append(data+'<br />');
        });
    </script>
</body>

and here is the server side js (app.js):

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);

server.listen(3000);

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

io.sockets.on('connection',function(socket){
    socket.on('send message', function(data){
        io.sockets.emit('new message',data);
    });
});

I know you guys won't need this but this is package.json:

{
"name":"test_chat_application",
"version":"0.0.1",
"private":"true",
"dependencies":{
    "socket.io":"1.4.8",
    "express":"4.14.0"
}

}

basically i think the problem is the page refresh! please help..


回答1:


You have to ditch the form, update some of the stuff (like var socket = io() instead of var socket = io.connect() and stuff) and handle your send button with onclick events instead of form submissions. That way you won't refresh.

Anyway, the updated server.js:

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);

server.listen(3000);

app.use(express.static('./'));

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

io.on('connection',function(socket){
  console.log('SOMEONE CONNECTED:', socket.id);

  socket.on('send', function(data){
    console.log(data);
    io.sockets.emit('new', data);
  });
});

index.html

<body>
<h1>Open chat</h1>
<div class="chat">
        <ul id="messages">

        </ul>
</div>
<hr />
<input size="28" type="text" id="message" />
<input type="button" onclick="send()" value="send" />

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
        var socket = io();

        function send(){
            var message = document.getElementById("message").value;
            socket.emit("send", { "message" : message });
            document.getElementById("message").value = "";
        }

  socket.on("new", function(data){
            console.log("NEW MESSAGE : ", data);
            var chatMessage = document.createElement("li");
            chatMessage.innerHTML = data.message;
    document.getElementById("messages").appendChild(chatMessage)
  });
</script>

Try this and let me know if it works




回答2:


I think you should add return false to prevent the form from being 'really' submitted (and thus refreshing the page). Submit event is not bubbling I think, so e.preventDefault doesn't work in this case.

$message_form.submit(function(e){
  e.preventDefault();
  socket.emit('send message', $message_box.val());
  $message_box.val('');
  return false;         
})



回答3:


<div class="chat"></div> <!-- this is class -->

// But you are using

var $chat = $('#chat');

Also move chat container outside of form#send_message and use document.ready

this should work well

<div class="chat"></div>
<hr />
<form id="send_message">
    <input size="28" type="text" id="message" />
    <input type="submit" value="send" />
</form>

<script>
$(document).ready(function() {
    var socket = io.connect();
    var $message_form = $('#send_message');
    var $message_box = $('#message');
    var $chat = $('#chat');

    $message_form.submit(function(e){
        e.preventDefault();
        socket.emit('send message', $message_box.val());
        $message_box.val('');                   
    });
    socket.on('new message', function(data){
        $chat.append(data+'<br />');
    });
});
</script>

better way

As you are using socket (which kind of ajax) - you loose all benefits of form element, so simply don't use it

<div class="chat"></div>
<hr />
<input size="28" type="text" id="message"/>
<button id="send_message">send</button>
<script>
    $(document).ready(function() {
        var socket = io.connect();
        var $message_form = $('#send_message');
        var $message_box = $('#message');
        var $chat = $('#chat');

        $message_form.click(function(){
           socket.emit('send message', $message_box.val());
           $message_box.val('');                   
        });
        socket.on('new message', function(data){
            $chat.append(data+'<br />');
        });
    });
</script>


来源:https://stackoverflow.com/questions/38397302/socket-io-and-node-js-chat-does-not-display-on-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!