nodejs群聊和私聊

网站效果测试:

http://chat.zphteach.com/


自行安装,代码如下

先安装nodejs

服务器代码

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(83);
function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}   
io.on('connection', function (socket) {	
	//获取所有用户
	var user_list=socket.nsp.adapter.rooms;
	//将用户发送到页面
	io.emit("user_list",user_list);
	socket.on('disconnect', function () {
		io.emit("user_list",user_list);
	});
	
	socket.on('per2per',function(name,data){
		//console.log(socket.id);
		//console.log(data.user)
		var user=data.user.substr(2);
		//console.log(user)
		//console.log(data.content)
		if(data.user=='all'){
			io.emit("message",'all',data.content)
		}else{
			socket.broadcast.to(data.user).emit("message",name,data.content);
			socket.emit("message",user,data.content);
		}
		
	})
	
	//admin模块结束
		
});


客户端代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery-1.11.1.min.js"></script>
	<script src="js/socket.io-1.4.5.js"></script>
   <title>nodejs聊天</title>
   <link href="css/bootstrap.min.css" rel="stylesheet">
   <script src="js/bootstrap.min.js"></script>
</head>
<style>
	.panel-body{
		display:none;
	}
</style>
<body>
<div class="container">

   <h1 id="count"></h1>
	昵称id:<span id="self" style="color:red"/></span>
	发送给:<span id="friend" style="color:green" value="all"/>all</span>
   <div class="row">
      <div class="col-md-4" style="overflow:auto">
         <ul class="list-group" id="userlist" onclick="javascript:void(0)">
		   <li class="list-group-item">
			  <span class="badge">新</span>
			  24*7 支持
		   </li>
		</ul>
      </div>
      <div class="col-md-8" >
        
		<div class="panel panel-default" >
		  <!-- Default panel contents -->
		  <div class="panel-heading" >消息中心</div>
		  <div class="panel-body" id='text_all' style="height:500px; overflow:auto">
			<div class="well well-sm">all</div>
		  </div>
		</div>
		<input id="content"/>
		<button onclick="send()"  class="btn btn-success">send</button>
		
      </div>
   </div><br>
   
</div>


<script>
$("#text_all").css('display','block');
var socket = io('http://'+location.host+':83'); // TIP: io()
  socket.on('connect', function () { 
	$("#self").html(socket.id);//获取自己socke.id
	//获取用户列表
	socket.on('user_list',function(data){
		$("#userlist").empty();
		//console.log(data);
		var count=0;
		//所有人标签
		var text='<li class="list-group-item" value="all"><span id="badge_all" class="badge">0</span>all</li>'
		$("#userlist").append(text)
			
		for(var x in data){		
			//console.log(x)
			count++;
			var name=x;
			var self = x.substr(2)
			//生成用户列表
			if(self!=socket.id){
				var text='<li class="list-group-item" value="'+name+'"><span id="badge_'+self+'" class="badge">0</span>'+name+'</li>'
				$("#userlist").append(text)
			}
			if($("#text_"+self).length==0){
			  var panel='<div class="panel-body" id="text_'+self+'" style="height:500px; overflow:auto"><div class="well well-sm">和'+self+'私聊中心</div></div>'
				$('.panel').append(panel);
			}		
		}
		//$(".panel-body").hide();
		//$("#text_all").show();
		$("#count").html("在线人数:"+count);	
	})
	//来接受消息
	socket.on('message',function(name,data){
		//console.log(data);
		//console.log(name)
		//当前时间
		var myDate=new Date()
		var data_text='<div class="well well-sm">'+myDate.toLocaleString()+":"+data+'</div>'
		$("#text_"+name).append(data_text)
		//未读消息数+1		
		var val=$('#badge_'+name).html()
		//console.log(val)
		$('#badge_'+name).html(parseInt(val)+1)			
		//消息滚动到底部
		$("#text_"+name).scrollTop(99999999); 
	})
  });

  //消息发送
  function send(){
	 var content= $("#content").val();
	 //console.log(content.length)
	 var length=content.length
	 if(length==0){
		 alert("不能为空")
		 return false;
	 }else if(length>20){
		 alert("消息太长了")
		 return false;
	 }
	 var user= $("#friend").attr('value');
	 //console.log(content);
	 //console.log(user);
	 socket.emit("per2per",socket.id,{user:user,content:content});
  }
  //点击用户列表
  $(document).on("click",".list-group-item",function(){
	  $('.list-group-item').css('background-color','white')
	  $('.list-group-item').css('color','black')
	  $(this).css('background-color','green')
	  $(this).css('color','white')
	  var val= $(this).attr('value');
	  $("#friend").attr('value',val)
	  $("#friend").html(val)
	
		if(val!='all'){
		   val = val.substr(2)
		}
	  $(".panel-body").hide();
	  $("#text_"+val).show();	  
  })
  

</script>
</body>
</html>


你可能感兴趣的:(nodejs群聊和私聊)