node socket的基本通讯

//1.服务端

var server =http.createServer(main).listen(8000, function() {
console.log("监听8000端口");
});
var userIds=[]; //储存连接上服务器的客户端id
main.use('/', express.static(__dirname + '/public'))
io = require('socket.io').listen(server); //引入socket.io模块并绑定到服务器
//socket部分
io.on('connection', function(socket) {
socket.on('init', function(data) { //获取userid 并返回客户端
userIds.push({name:data.name,id:socket.id});
socket.emit('syu',socket.id);
//有用户连接 返回好友列表
socket.broadcast.emit('friendsList',userIds); //除此客户端 全部返回
socket.emit('friendsList',userIds); //只此客户端返回
});
socket.on('chat', function(data) { //聊天时获取 客户端聊天对象及聊天内容
if(data){
io.to(data.chatid).emit(data.chatid,{name:data.name,text:data.text}); //给指定客户端发消息
}
});
socket.on('all', function(data) {
console.log(data);
if(data){
socket.broadcast.emit('alls',{name:data.name,text:data.text}); //群发
}
});
});
main.get('/',(res, req, next)=>{
req.sendfile('./public/chat.html');
});
//2.客户端
  1.html 必须引入<script src="/socket.io/socket.io.js"></script>
  2.js代码语句
    
<script type="text/javascript">
var chatName='';
let userId='';
var userName='';
var socket=io.connect();//与服务器进行连接
getName();
function getName() { //必输登陆名
var a =prompt('请输入name');
if(!a){
getName();
}else{
userName=a;
socket.emit('init',{name:userName}); ////初始与服务器通信
}
}
getUserId(function(){
//获取自己的id;
socket.on(userId,function(data){ //获取好友发送回来消息
console.log(data);
create(data,'friendMassage');
});
})
button=document.getElementById('sendBtn');
function sends(type){ //点击与选择好友发送信息
if(!chatName){
chatName=userId
}
var chat='chat' //私聊
if(type==2){ //群发
chat='all'
}
socket.emit(chat,{name:userName,chatid:chatName,text:document.getElementById('sendtext').value});
create({name:userName,text:document.getElementById('sendtext').value},'myMassage');
document.getElementById('sendtext').value='';
}
function create(data,className){ //创建新信息
var newP=document.createElement('p');
newP.textContent=data.name+'--'+data.text;
newP.className=className
document.getElementsByClassName('showMessage')[0].appendChild(newP);
}
socket.on('friendsList',function(data){ //好友列表返回
console.log(data);
document.getElementById('friends').innerHTML='';
for (var i=0;i<data.length;i++){
var li=document.createElement('li');
li.textContent=data[i].name;
li.setAttribute('id',data[i].id);
document.getElementById('friends').appendChild(li);
li.onclick=function () {
let oldLi=document.getElementById('friends').childNodes;
for(var a=0;a<oldLi.length;a++){//清空选中li
oldLi[a].className='';
}
this.className='current';
chatName=this.getAttribute('id');
}
}
})
function getUserId(fun){
socket.on('syu',function (userIds) {
userId=userIds
console.log(userIds);
fun();
})
}
socket.on('alls',function(data){ //接收群发消息
create(data,'friendMassage');
});
</script>
 
posted @ 2017-09-04 13:52  小贱贱!  阅读(174)  评论(0)    收藏  举报