我使用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);
});
});
感谢您的时间.
解决方法:
这是一个想法:为你的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>");
});
最终结果是您可以根据用户名或任何其他令您满意的标准指定颜色.