NodeJSとSockett.IOはチャットルームの応用を構築します.

7027 ワード

NodeJSとSockett.IOに基づく簡単なチャットルームプログラムです.
index.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/index.css" />
<title></title>
</head>
<body>
<div class="login">
	<input type="text" id="username" placeholder="        " />
	<input type="button" id="login_btn" value="  " />
	<span>      ,      </span>
</div><!--login-->
<div class="box-1">
	<div class="content">
		<ul>
		</ul>
	</div><!--content-->
	<div class="box-2">
		<input type="text" id="send_content" />
		<input type="button" id="send_btn" value="  " disabled="true" class="active" />
	</div><!--box-2-->
</div><!--box-1-->
<div class="box-3">
	<h2>    </h2>
	<ul>
	</ul>
</div><!--box-3-->
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/socket.io.js"></script>
<script>
(function(){

	var w = window;

	w.CHAT = {
		username : null,
		socket : null,
		send_btn : $('#send_btn'),
		send_content : $('#send_content'),
		login_btn : $('#login_btn'),
		login_span : $('.login span'),
		ul : $('.content ul'),
		username_input : $('#username'),
		user_list : $('.box-3 ul'),
		start : function(){
			this.login_btn.on('click',function(){
				CHAT.login();
			})
		},
		init : function(){
			this.socket = io('ws://localhost:8080/');
			this.socket.on('connect',function(){
				console.log('       ');
			})
			this.socket.on('message',function(data){
				CHAT.showMessage(data);
			})
			this.socket.on('login',function(data){
				CHAT.updateUserList(data.list);
			})
			this.socket.on('leave',function(data){
				console.log(data.username + '     ');
				CHAT.updateUserList(data.list);
			})
			this.send_btn.on('click',function(){
				CHAT.sendMessage();
			})
			this.send_content.keypress(function(event){
				if(event.which === 13){
					event.preventDefault();
					CHAT.sendMessage();
				}
			})
		},
		//  
		login : function(){
			var username_val = $.trim(this.username_input.val());
			if(username_val !== ''){
				this.username = username_val;
				this.init();
				this.socket.emit('login',{username : username_val});
				this.login_span.html(username_val + '    ');
				this.send_btn.removeClass('active').prop('disabled',false);
				this.login_btn.addClass('active').prop('disabled',true);
			}else{
				alert('        ');
			}
		},
		//    
		sendMessage : function(){
			var content = $.trim(this.send_content.val());
			if(content === ''){
				alert('      ');
				return false;
			}
			this.socket.emit('message',{username : this.username,content : content});
			this.send_content.val('');
		},
		//    
		showMessage : function(data){
			this.ul.append('<li><time>' + this.getTime() + '</time>' + data.username + ' :' + data.content + '</li>');
			//         
			this.ul.scrollTop(this.ul.height());
		},
		//      
		updateUserList : function(data){
			var username = data.split(','),
				str = '';
			for(var i=0,len=username.length;i<len;i++){
				str += '<li>' + username[i] + '</li>';
			}
			this.user_list.html(str);
		},
		//    
		getTime : function(){
			var date = new Date(),
				str = date.getFullYear() + ' ' + (date.getMonth() + 1) + ' ' + date.getDate() + '  ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
			return str;
		}
	}

	CHAT.start();

})()
</script>
</body>
</html>
index.css
body{width:100%; font-size:12px;}
.login{width:600px; height:40px; margin-top:100px; margin-left:100px;}
.login #username{width:200px; height:38px; border:1px solid #505155; text-indent:10px;}
.login #login_btn{width:98px; height:40px; background-color:#F02729; color:#FFF; border:0;}
.login #login_btn.active{background-color:#838389;}
.login span{margin-left:20px;}
.box-1{width:600px; height:400px; border:1px solid #505155; margin-left:100px; margin-top:20px; float:left;}
.box-1 .content{width:100%; height:339px; border-bottom:1px solid #505155; overflow:hidden;}
.box-1 .content ul{width:90%; height:319px; margin-left:5%; margin-top:10px; overflow-x:hidden; overflow-y:auto; float:left;}
.box-1 .content ul li:not(:nth-child(1)){margin-top:10px;}
.box-1 .content ul li time{display:block; width:100%;}
.box-1 .box-2{width:100%; height:60px;}
.box-1 .box-2 #send_content{width:450px; height:40px; border:1px solid #505155; margin-top:9px; margin-left:20px; float:left; text-indent:10px;}
.box-1 .box-2 #send_btn{width:98px; height:42px; margin-top:9px; margin-left:15px; float:left; background-color:#F02729; color:#FFF; border:0;}
.box-1 .box-2 #send_btn.active{background-color:#838389;}
.box-3{width:200px; height:400px; border:1px solid #505155; float:left; margin-top:20px; margin-left:15px; overflow-x:hidden; overflow-y:auto;}
.box-3 h2{font-size:14px; text-align:center; height:40px; line-height:40px;}
.box-3 ul{width:90%; margin-left:5%;}
.box-3 ul li{width:100%; height:25px; line-height:25px;}
server.js
var http = require('http'),
	io = require('C:/Users/Administrator/AppData/Roaming/npm/node_modules/socket.io');

var server = http.createServer(function(req,res){
	res.writeHead(200,{
		'Content-Type' : 'text/html'
	});
})
server.listen(8080);

var socket = io.listen(server);

//    
var users = [];

socket.on('connection',function(client){
	console.log('        ');

	client.on('login',function(data){
		client.name = data.username;
		if(users.indexOf(data.username) === -1){
			users.push(data.username);
			socket.emit('login',{list : users.join()});
		}else{
			console.log('       ');
		}
	})

	client.on('message',function(data){
		socket.emit('message',{username : data.username,content : data.content});
	})

	client.on('disconnect',function(){
		if(client.name !== 'undefined'){
			console.log(client.name + '      ');
			var index = users.indexOf(client.name);
			if(index !== -1){
				//     
				users.splice(index,1);
				socket.emit('leave',{username : client.name,list : users.join()});
			}
		}
	})

})
注意:Node環境でserver.jsを実行し、ブラウザでクライアントを開けばチャットにログインできます.
参照リンク:http://www.plhwin.com/2014/05/28/nodejs-socketio/