NodeJS + Socket.io聊天应用程序每次发送新消息时都会建立新的连接

时间:2017-09-15 15:17:42

标签: javascript node.js sockets socket.io

我正在使用socket.io开发一个实时聊天室。按“发送”按钮后,页面将重新加载并建立新连接。我知道我错过了javascript代码的位置。

我遵循了本教程http://javabeginnerstutorial.com/javascript-2/create-simple-chat-application-using-node-js-express-js-socket-io/#comment-4868,但无法使代码生效。尝试了所有可能的模式。

server.js

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

app.set('port', (process.env.PORT || 3000));

app.get('/', function(req, res) {
var express = require('express');
app.use(express.static(path.join(__dirname)));
res.sendFile(path.join(__dirname, '../ATTEMPT-2', 'index.html'));
});


io.on('connect', function(socket) {

console.log('A new user is connected'); 

    socket.on('chatMessage', function(from, msg) {
        io.emit('chatMessage', from, msg);
    });

    socket.on('notifyUser', function(user) {
        io.emit('notifyUser', user);
    });
});




http.listen(app.get('port'), function() {
    console.log('The application is running on port ' + app.get('port'));
});

chat.js

$(document).ready(function() {

var socket = io();

function submitFunction() {

    var from = $('#user').val();
    var message = $('#m').val();

    if (message != '') {

        socket.emit('chatMessage', from, message);
    }

    $('#m').val('');
    return flase;
}


function notifyTyping() {
    var user = $('#user').val();
    socket.emit('notifyUser', user);
}

socket.on('chatMessage', function(from, msg) {
    var me = $('#user').val();
    var color = (from == me) ? 'green' : '#009afd';
    var from = (from == me) ? 'Me' : from;
    $('#messages').append('<li><strong style="color:' + color + '">' + from 
    + '</strong>:' + msg + '</li>');
});


socket.on('notifyUser', function(user) {
    var me = $('#user').val();
    if (user != me) {
        $('#notifyUser').text(user + 'is typing...');
    }
    setTimeout(function() {
        $('#notifyUser').text('');
    }, 10000);
});

// CREATE USERS
var name = makeId();

$('#user').val(name);

socket.emit('chatMessage', 'System', '<strong>' + name + '</strong> has 
joined the conversation!');
});


function makeId() {
    var text = "";
    var possible = 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

     for (var i = 0; i < 5; i++) {
        text += possible.charAt(Math.floor(Math.random()*possible.length));
    }
    return text;
}

index.html - &gt;只推出重要部分

<head>
   <title>Chat App | DB</title>
   <link rel="stylesheet" href="css/main.css">

   <script src="/socket.io/socket.io.js"></script>
   <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
   <script src="chat.js"></script>
</head>

<body>
<div class="chat">
    <input type="text" class="chat-name" placeholder="Enter your name">
    <div class="chat-messages">
        <ul id="messages"></ul>
        <span id="notifyUser"></span>
    </div>

    <div id="sending-form">
    <form id="form" action="" onsubmit="return submitFunction();">
    <input type="hidden" id="user" value="" />
    <input id="m" autocomplete="off" onkeyup="notifyTyping();" 
    placeholder="Type yor message here.." />
    <input type="button" class="btn btn-primary" id="send-btn" value="Send">
    </form>
    </div>
    </div>
</body>

1 个答案:

答案 0 :(得分:0)

每次提交新表单的原因是每次提交表单时,页面都会刷新,因此每次刷新时都会调用var socket = io();,因此与服务器建立新连接。考虑每次要发送表单时执行AJAX请求,或覆盖表单的默认刷新行为。