在NodeJS聊天应用

时间:2015-11-11 12:10:06

标签: javascript jquery html css chat

我使用NodeJS和socket.io创建了一个聊天室。它允许多个用户连接到具有不同用户名的聊天室。

它运行正常,但我希望我的消息颜色与其他用户的消息不同。我在CSS中使用了奇怪的逻辑,但如果我同时发送2条消息,这种方法就不会有效。

这是我的 Index.html

    <div id="wrapper">
    <div id="usernameWrap">
        <p id="usernameError"></p>
        <form id="setUsername">
            <input class="message" id="username" placeholder="Enter your Username"/>
            <input class="button" type="submit" value="SUBMIT"/>
        </form>
    </div>

    <div id="chatWrapper">
        <ul id="chat"></ul>
        <form id="send-message">
            <input class="message" type="text" id="message" placeholder="Type a message" autocomplete="off" />
            <input class="button" type="submit" value="SEND"/>
        </form>
    </div>
</div>
    <script src="/socket.io/socket.io.js"></script>
    <Script>
        jQuery(function($){
            var socket =io.connect();
            var $usernameForm = $('#setUsername');
            var $usernameError = $('#usernameError');
            var $username = $('#username');
            var $messageForm = $('#send-message');
            var $messageBox = $('#message');
            var $chat = $('#chat');

            /* setting username */

            $usernameForm.submit(function(e){
                e.preventDefault();
                socket.emit('new user',$username.val(),function(data){
                    if(data){
                        $('#usernameWrap').hide();
                        $('#chatWrapper').show();
                    } else{
                        $usernameError.html('Username is already Taken!');
                    }
                });
                $username.val('');
            });

            /* sending and receiving messages */

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

            socket.on('new message',function(data){
                $chat.append('<li><b>' + data.username + ': </b>' + data.message + "<br/></li>");
            });
        });
    </Script>

这是我的 App.js 文件:

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

app.use('/css', express.static(__dirname + '/css'));

server.listen(8081);

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

io.sockets.on('connection',function(socket){
    socket.on('new user',function(data,callback){
        if(usernames.indexOf(data) != -1){
            callback(false);
        } else{
            callback(true);
            socket.username = data;
            usernames.push(socket.username);
            io.sockets.emit('usernames',usernames);
        }
    });

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

    socket.on('disconnect',function(data){
        if(!socket.username) return;
        usernames.splice(usernames.indexOf(socket.username),1);
    });
});

感谢您的时间。

4 个答案:

答案 0 :(得分:3)

这是一个想法:为你的css添加一些颜色类:

.blueText {
    color: #00F;
}
.greenText {
    color: #0F0;
}

现在让服务器根据用户名分配颜色类:

socket.on('send message',function(data){
    var userColorClass = "greenText";
    if( socket.username === "root" ) {
        userColorClass = "blueText";
    }
    io.sockets.emit('new message',{
        message:data,
        colorClass: userColorClass,
        username:socket.username
    });
});

最后,在浏览器JavaScript代码中添加类名:

        socket.on('new message',function(data){
            $chat.append('<li class="' + data.colorClass + '"><b>' +
                data.username + ': </b>' + data.message + "<br/></li>");
        });

最终结果是您可以根据用户名或任何其他令您满意的标准指定颜色。

答案 1 :(得分:0)

向聊天记录添加消息时,请检查data.username是否与当前用户相同。如果是,请将一个类添加到您正在创建的DOM元素中。使用CSS为该类指定一种特殊样式。

答案 2 :(得分:0)

Thank you for your answers Hughes and Lee, I used your suggestions and solved the problem.

I stored the use name entered by the user in a variable and checked it with data.username.

I'm attaching the new index.html and app.js file:

Index.html

<!doctype html>
<html>
<head>
    <title>Socket.IO chat</title>
    <!-- styles -->
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- scripts -->
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>

</head>
<body>
<div id="wrapper">
    <div id="usernameWrap">
        <p id="usernameError"></p>
        <form id="setUsername">
            <input class="message" id="username" placeholder="Enter your Username"/>
            <input class="button" type="submit" value="SUBMIT"/>
        </form>
    </div>

    <div id="chatWrapper">
        <ul id="chat"></ul>
        <form id="send-message">
            <input class="message" type="text" id="message" placeholder="Type a message" autocomplete="off" />
            <input class="button" type="submit" value="SEND"/>
        </form>
    </div>
</div>
    <script src="/socket.io/socket.io.js"></script>
    <Script>
        jQuery(function($){
            var socket =io.connect();
            var $usernameForm = $('#setUsername');
            var $usernameError = $('#usernameError');
            var $username = $('#username');
            var $messageForm = $('#send-message');
            var $messageBox = $('#message');
            var $chat = $('#chat');
            var $currentUser;

            /* setting username */

            $usernameForm.submit(function(e){
                e.preventDefault();
                socket.emit('new user',$username.val(),function(data){
                    if(data){
                        $('#usernameWrap').hide();
                        $('#chatWrapper').show();
                    } else{
                        $usernameError.html('Username is already Taken!');
                    }
                });
                $currentUser = $username.val();
                $username.val('');
            });

            /* sending and receiving messages */

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

            socket.on('new message',function(data){
                if(data.username === $currentUser){
                    data.colorClass = "blueText";
                } else{
                    data.colorClass = "greenText";
                }
                $chat.append('<li class="' + data.colorClass + '"><b>' + data.username + ': </b>' + data.message + "<br/></li>");
            });
        });
    </Script>
</body>
</html>

App.js:

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

app.use('/css', express.static(__dirname + '/css'));

server.listen(8081);

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

io.sockets.on('connection',function(socket){
    socket.on('new user',function(data,callback){
        if(usernames.indexOf(data) != -1){
            callback(false);
        } else{
            callback(true);
            socket.username = data;
            usernames.push(socket.username);
            io.sockets.emit('usernames',usernames);
        }
    });

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

    socket.on('disconnect',function(data){
        if(!socket.username) return;
        usernames.splice(usernames.indexOf(socket.username),1);
    });
});

答案 3 :(得分:0)

这个解决方案对我有用。我正在寻找对齐发送者消息并左对齐接收者消息。在其他人贡献的基础上,我想出了这个。它是完全动态的。

// initializing socket.io on the client
let socket = io();

// I will be storing a socket.id client side in this variable
// each client connected should have a unique socket.id 
let clientSocketId;

// send the clientSocketId when you emit the event from the browser to the server. 
 $messageForm.submit(function(e){
        e.preventDefault();
        
        // storing the unique socket id 
        clientSocketId = socket.id;
        
        // emit your data as usual
        socket.emit('send message', {
          message: $messageBox.val(),
          username: $username.val(),
          clientId: clientSocketId
        });
        $messageBox.val('');
      });
      

// On the server now. I am using version 2.0.4
io.on('connection', function(socket){
  console.log('a user is connected');
  
  socket.on('send message', function(data) {
    
    io.emit('new message', { 
      message: data.message,
      username: data.username,
      clientId: data.clientId
    })
    
  })
})

// back in the browser
socket.on('new message', function(data){

  // check if the clientSocketId return from the server data.clientId is the same that was sent by browser/client clientSocketId
  
  if(clientSocketId === data.clientId) {

    $chat.append('<li class='blueText'><b>' + data.username + ': </b>' + data.message + "<br/></li>");
  } else {
  $chat.append('<li class='greenClass'><b>' + data.username + ': </b>' + data.message + "<br/></li>");
  }
  
})
.blueText {
    color: #00F;
}
.greenText {
    color: #0F0;
}