未在socket.io / node.js

时间:2016-10-28 04:22:00

标签: javascript node.js socket.io

我在nodejs和socket.io here中创建了一个原始聊天室,我试图让它只向用户显示用户名和欢迎消息,以及显示所有其他用户的消息他/她加入这里是我的代码

服务器代码

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

app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});

io.on('connection', function (socket) {
socket.on('adduser', function(username){
socket.username = username;
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected to  this room' + '<hr>');
socket.emit('welcomeuser', 'SERVER Welcome', username  + '<hr>');

});
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconected');
});

 socket.on('chat-message', function (message) {
 console.log('message : ' + message.text);
 //excludes "socket" from getting the emit
 socket.broadcast.emit("chat-message",message);
 });
 });

这是我的客户代码

    var username = "";
    var socket = io();

    socket.on('connect', function(){
        socket.emit('adduser', prompt("What's your name?"));
    });
    socket.on('updatechat', function (username, data) {
        $('#chatlog-display-div').append('<b>'+username + ':</b> ' + data + '<br>');
    });
    socket.on('welcomeuser', function(username, data){
        jQuery("#chatlog-display-div").append( username +'<hr>');
    });
     $('form').submit(function(e) {
     e.preventDefault();

           //gets the value from the message text feild and sets it as the    message var
     var message = {
            text : $('#chat-box-div-txtinpt').val()
            }
        if (message.text.trim().length !== 0) {
                        socket.emit('chat-message',message);
                //append the message to the chatlog-display-div
                $('#chat-box-div-txtinpt').focus().val('');
                jQuery("#chatlog-display-div").append('<div>'+message.text+'</div><hr>');
                   }
    });
    //clear the value of the txtinput after you focus it.

           socket.on('chat-message', function (message) {
           jQuery("#chatlog-display-div").append('<div>'+message.text+'</div><hr>');
           });

有人可以帮助我吗

0 个答案:

没有答案