实时聊天 [记录]
<script type="text/javascript" src="${ctxPath}/libs/jquery.min.js"></script> --基础 <script type="text/javascript" src="${ctxPath}/libs/lodash.min.js"></script> <script type="text/javascript" src="${ctxPath}/live/sockjs.min.js"></script> --时事通讯 <script type="text/javascript" src="${ctxPath}/live/vertxbus.js"></script> --对socket进行封装的js
var _opt={};
var el=$("#data");
_opt={
id:el.attr('data-id'),room:el.attr('data-room'),cusid:el.attr('data-cusid'),name:el.attr('data-name'),url:el.attr('data-url')
}
//创建群通话客户端
var eb = new vertx.EventBus(_opt.url); url-后台配置的服务地址 如:http://192.168.10.178:82/eventbus
eb.onopen = function () {
var msg = {"serverId": _opt.room,"clientId": _opt.cusid,"clientName":_opt.name,"type": 0,"body": ""};
//群组ID - 房间号|房间id 统一房间号才能再聊天室聊天 //当前客户ID //当前客户名称 //消息类型 //消息内容 msg 参数自定义 与后台协商
//监听客户端通信 监听-方法为后台广播配置后广播发送回来的信息
eb.registerHandler("client_" + _opt.cusid + ":" + _opt.room, msg, function (msg) {
switch (msg.type) {
case 0:cus.online(msg);break;
case 1:cus.msg(msg);break;
case 2:cus.goout(msg);break;
case 3:mineOnline(msg);break;
}
//登录之后 登录本人走3 初始化本地人员列表(为了统计在线人数以及拉黑禁言操作)
//广播出来 别人接收信息 走0 有用户上线
});
};
var cusList=[]; //本地用户列表 存储
var cus={
online:function (msg) { //用户上线了
cusList.push({"clientId": msg.clientId,"writeHandlerId": msg.writeHandlerId,"name": msg.clientName});
//客户ID //系统分配的客户ID //客户名称
cusCount();
},
goout:function (msg) { //用户下线了 //根据客户ID删除本地客户
_.remove(cusList, function (c) {
return c.clientId == msg.clientId;
});
cusCount();
},
msg:function (msg) { //有用户发言了
$('#chat').append('<li><span data-id="'+msg.clientId+'" onclick="cusHandle(\''+msg.clientId+'\',\''+msg.clientName+'\')">'+msg.clientName+':</span>'+msg.body+'</li>')
}
}
function mineOnline(msg) { //本用户登录 获取服务器端存的用户列表
cusList = JSON.parse(msg.body);
cusCount();
}
function cusHandle(id,title) {
layer.confirm(title, {
btn: ['禁言', '拉黑'],title: false,area: ['300px', '160px'],shadeClose: true,scrollbar: false
}, function () {
cusSilent(id);
}, function () {
cusBlacklist(id);
});
}
function cusCount() {
$("#cusCount").text(cusList.length);
}
发送消息 function send(event) { if (event.keyCode == 13 || event.which == 13) { var message = $('#message').val(); if (message.length > 0) { var msg = { "serverId": $('#serverId').val(), "clientId": $('#clientId').val(), "clientName": $('#clientName').val(), "type": 1, "body": message }; //所有通讯统一发送server服务器 eb.send("server", msg); $('#message').val(""); } } }