Signalr,能够跨域,通过Group分组发送组内消息

项目中要用,因为百度的太多,我也不记得哪些地方的资源我这边使用了。记录一下怎么用的

引用框架如下:
Signalr,能够跨域,通过Group分组发送组内消息_第1张图片

Model实体文件为:SignalRModel.cs
项目实际使用页面: NewLiving.cshtml

Hub集线器方法

using eduSystem.DataAccess.Entity;
using eduSystem.DataAccess.SensitiveWord;
using eduSystem.DataAccess.SqlHelper;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Web;

namespace eduSystem.SignalR
{
     

    [HubName("ServerHub")]
    public class ServerHub : Hub
    {
     
        public void Hello()
        {
     
            Clients.All.hello();
        }

        public static SignalRModel db = new SignalRModel();

        /// 
        /// 重写Hub连接事件
        /// 
        /// 
        public override System.Threading.Tasks.Task OnConnected()
        {
     
            return base.OnConnected();
        }

        //用户进入页面时执行的(连接操作)
        public void userConnected(int pid, string type, int suid = 99)
        {
     
            string roomname = "";
            type = HttpUtility.HtmlEncode(type);
            try
            {
     

                //使用dapper  直接查询数据库信息
                //获取老师信息
                string sql = "select * from edu_teacher where Id=(select TeacherId from edu_vediochapterstruct where Id=@Id)";
                edu_teacher teacher = SqlDapperHelper.ExecuteReaderReturnT<edu_teacher>(sql, new {
      Id = pid });


                //获取课程信息
                string sql1 = "select * from edu_vediochapterstruct where Id=@Id";
                edu_vediochapterstruct vediochapterstruct = SqlDapperHelper.ExecuteReaderReturnT<edu_vediochapterstruct>(sql1, new {
      Id = pid });

                //获取用户信息
                edu_users users = new edu_users();
                string sql2 = "select * from edu_users where Id=@Id";
                if (suid != 0)
                {
     
                    //学生User信息
                    users = SqlDapperHelper.ExecuteReaderReturnT<edu_users>(sql2, new {
      Id = suid });
                    //判断用户是否存在
                    var user = db.Users.Where(w => w.UserName == Context.ConnectionId).FirstOrDefault();
                    if (user == null)
                    {
     
                        user = new User()
                        {
     
                            UserName = Context.ConnectionId,
                            RealName = users.Account,
                            HeadImg = users.HeadeImg,
                            type = 0//学生
                        };
                        db.Users.Add(user);
                    }
                }
                else
                {
     
                    //教师User信息
                    users = SqlDapperHelper.ExecuteReaderReturnT<edu_users>(sql2, new {
      Id = vediochapterstruct.UserId });
                    //判断用户是否存在
                    var user = db.Users.Where(w => w.UserName == Context.ConnectionId).FirstOrDefault();
                    if (user == null)
                    {
     
                        user = new User()
                        {
     
                            UserName = Context.ConnectionId,
                            RealName = teacher.Name,
                            HeadImg = teacher.HeadImg,
                            type = 1//老师
                        };
                        db.Users.Add(user);
                    }
                }

                //课程名称 + 老师Id组成房间名称
                roomname = vediochapterstruct.Name.ToString() + vediochapterstruct.TeacherId.ToString();
                object userlist;

                //判断身份
                switch (type)
                {
     
                    //老师
                    case "teacher":

                        //创建房间
                        CreateRoom(roomname);

                        //发送自己的房间名
                        Clients.Caller.getRoomName(roomname);

                        //通知房间所有人我上线了
                        Clients.OthersInGroup(roomname).sendMessage(roomname, "
  • 【" + teacher.Name + "】:" + DateTime.Now.ToString(" HH:mm:ss ") + 加入房间
  • "
    ); //通知自己上线了 Clients.Caller.sendMessage(roomname, "
  • 【" + teacher.Name + "】:" + DateTime.Now.ToString(" HH:mm:ss ") + 加入房间
  • "
    ); //发送信息给自己,并显示自己 userlist = JsonConvert.SerializeObject(db.Users.FirstOrDefault(r => r.UserName == Context.ConnectionId)); Clients.Caller.getTeaList(userlist); break; //学生 case "student": //加入房间 AddRoom(roomname); //发送自己的房间名 Clients.Caller.getRoomName(roomname); //通知房间其他人我上线了 Clients.OthersInGroup(roomname).sendMessage(roomname, "
  • 【" + users.Account + "】:" + DateTime.Now.ToString(" HH:mm:ss ") + 加入房间
  • "
    ); //通知自己上线了 Clients.Caller.sendMessage(roomname, "
  • 【" + users.Account + "】:" + DateTime.Now.ToString(" HH:mm:ss ") + 加入房间
  • "
    ); //获取在线老师 var teacherlist = JsonConvert.SerializeObject(db.Users.FirstOrDefault(r => r.type == 1)); Clients.Caller.getTeaList(teacherlist); //发送信息给自己,并显示在线学员 var rooms = db.Rooms.FirstOrDefault(p => p.RoomName == roomname); userlist = JsonConvert.SerializeObject(rooms.Users.Where(r => r.type == 0)); Clients.Caller.getList(userlist); //获取上线用户 Clients.OthersInGroup(roomname).addList(Context.ConnectionId, users.Account, users.HeadeImg); break; default: SendMsg(roomname, "
  • " + DateTime.Now.ToString(" HH:mm:ss ") + 身份获取失败,请联系管理员
  • "
    ); break; } } catch (Exception ex) { SendMsg(roomname, "
  • " + DateTime.Now.ToString(" HH:mm:ss ") + 服务器连接失败,请重试!" + ex.Message.ToString() + "
  • "
    ); } } /// /// 更新所有用户的房间列表 /// private void GetRooms() { var rooms = JsonConvert.SerializeObject(db.Rooms.Select(p => p.RoomName).ToList()); Clients.All.getRoomList(rooms); } /// /// 重写Hub链接断开事件 /// /// /// public override System.Threading.Tasks.Task OnDisconnected(bool s) { //var user = db.Users.Where(u => u.UserName == Context.ConnectionId).FirstOrDefault(); 判断用户是否存在,存在则删除 //if (user != null) //{ // //删除用户 // db.Users.Remove(user); //} return base.OnDisconnected(s); } /// /// 加入聊天室 /// /// public void AddRoom(string roomName) { //查询聊天室 var room = db.Rooms.Find(a => a.RoomName == roomName); //存在则加入 if (room != null) { //查找房间中是否存在此用户 var isUser = room.Users.Where(w => w.UserName == Context.ConnectionId).FirstOrDefault(); //不存在则加入 if (isUser == null) { var user = db.Users.Find(a => a.UserName == Context.ConnectionId); //user.Rooms.Add(room); room.Users.Add(user); Groups.Add(Context.ConnectionId, roomName); } else { Clients.Client(Context.ConnectionId).sendMessage(roomName, "请勿重复加入房间"); } } } /// /// 创建聊天室 /// /// public void CreateRoom(string roomName) { string message = ""; var room = db.Rooms.Find(a => a.RoomName == roomName); if (room == null) { Room r = new Room() { RoomName = roomName }; //将房间加入列表 db.Rooms.Add(r); //加入房间 AddRoom(roomName); } else { var my = db.Users.FirstOrDefault(r => r.UserName == Context.ConnectionId); message = "
  • 【" + my.RealName + "】:" + DateTime.Now.ToString(" HH:mm:ss ") + 已存在房间,正在加入
  • "
    ; Clients.Group(roomName).sendMessage(roomName, message); AddRoom(roomName); //Clients.Client(Context.ConnectionId).sendMessage(roomName, message); } } /// /// 退出聊天室 /// /// public void ExitRoom(string roomName) { //查找房间是否存在 var room = db.Rooms.Find(a => a.RoomName == roomName); //查找用户是否存在 var myuser = db.Users.FirstOrDefault(r => r.UserName == Context.ConnectionId); //发送下线用户消息 string msg = "
  • 【" + myuser.RealName + "】:" + DateTime.Now.ToString(" HH:mm:ss ") + 已下线
  • "
    ; Clients.Group(roomName).sendMessage(roomName, msg); //判断用户是否存在,存在则删除 if (myuser != null) { //删除用户 db.Users.Remove(myuser); } //移除下线用户 Clients.OthersInGroup(roomName).removeList(Context.ConnectionId); //存在则删除 if (room != null) { //查找要删除的用户 var user = room.Users.Where(p => p.UserName == Context.ConnectionId).FirstOrDefault(); //移除此用户 room.Users.Remove(user); //如果房间人数为0,怎删除房间 if (room.Users.Count == 0) { db.Rooms.Remove(room); } //Groups Remove移除分组方法 Groups.Remove(Context.ConnectionId, roomName); //提示客户端 //Clients.Client(Context.ConnectionId).removeRoom("退出成功"); } } /// /// 给分组内所有用户发送消息 /// /// /// public void SendMsg(string Room, string Message) { Clients.Group(Room).sendMessage(Room, Message); } /// /// 给分组内所有用户发送消息 /// /// /// public void SendHtmlMsg(string Room, string Message) { FilterHelper filter = new FilterHelper(HttpContext.Current.Server.MapPath("../Filter.txt")); //存放敏感词的文档 filter.SourctText = Message.ToString().Trim(); string resultStr = filter.Filter('*'); //Clients.Group(Room, new string[0]).sendMessage(Room, Message + " " + DateTime.Now.ToString()); //拿当前连接人信息 var user = db.Users.FirstOrDefault(r => r.UserName == Context.ConnectionId); string msg = ""; if (Message.Length <= 200) { msg = "
  • 【" + user.RealName + "】:" + resultStr + "
  • "
    ; Clients.Group(Room).sendMessage(Room, msg); } else { msg = "
  • 最多发送200字
  • "
    ; Clients.Caller.sendMessage(Room, msg); } } } }

    页面实际调用

    
    @{
         
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>在线教学</title>
        <link href="~/Content/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    </head>
    <body>
        <div class="head">
            <img src="~/images/pc_living.png" />
        </div>
        <div class="content">
            <div class="thdiv">
                <div class="col-lg-3 col-md-3">
                    <div class="peoples">
                        <div class="teacher">
                            <h4>讲师</h4>
                            <p id="teacheronly">
                                @*<img src="https://b-ssl.duitang.com/uploads/item/201509/25/20150925110828_iMnGx.jpeg" alt="" />
                                    <span class="teachername">龙晗</span>*@
                            </p>
                        </div>
                        <div class="teacher tea-box">
                            <h4>学员<span id="count">0</span></h4>
                            <div class="student" id="studentlist">
                                @*<p>
                                        <img src="https://b-ssl.duitang.com/uploads/item/201509/25/20150925110828_iMnGx.jpeg" alt="" />
                                        <span class="teachername">啊啊啊啊晗</span>
                                    </p>*@
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6">
                    <div class="obsinfo">
                        <h3>直播参数</h3>
                        <div class="form-horizontal">
                            <div class="form-group">
                                <label class="col-lg-2 ol-md-2 control-label">流类型</label>
                                <div class="col-lg-10 col-md-10">
                                    <p class="form-control-static">自定义流媒体服务器</p>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-2 ol-md-2 control-label">URL</label>
                                <div class="col-lg-10 col-md-10">
                                    @*<p class="form-control-static">rtmp://play.wxwedu.cn/live</p>*@
                                    <input type="text" class="form-control form-control-static" value="" readonly="readonly" id="playflow">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-2 ol-md-2 control-label">流名称</label>
                                <div class="col-lg-10 col-md-10">
                                    @*<p class="form-control-static">eWNoYXRfVmVkaW8xMjk_m</p>*@
                                    <input type="text" class="form-control form-control-static" value="" readonly="readonly" id="stream">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-md-3">
                    <div class="chat">
                        <div class="col-lg-12 col-md-12">
                            <h4>公告</h4>
                            <textarea class="form-control" readonly="readonly" rows="3"></textarea>
                        </div>
                        <div class="col-lg-12 col-md-12">
                            <div class="chatinfo">
                                <h4>互动聊天</h4>
                                <div class="messageBox">
                                    <ul id="messageList">
                                        <li><span style="color:#f3c804">正在连接服务器...</span></li>
                                    </ul>
                                </div>
                                <!-- Small button group -->
                                <div class="btn-group" style="display:none">
                                    <select class="form-control" id="sel1"></select>
                                </div>
                                <div class="btn-group" style="display:none">
                                    <button class="btn btn-default send" type="button" id="sendall">广播</button>
                                </div>
                                <div class="btn-group">
                                    <button class="btn btn-default send" type="button" id="clear">清除</button>
                                </div>
                                <div class="input-group">
                                    <input type="text" class="form-control" placeholder="请遵循平台协议发言!" id="sendmsg">
                                    <span class="input-group-btn">
                                        <button class="btn btn-default send" type="button" id="send">发送</button>
                                    </span>
                                </div><!-- /input-group -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="~/Content/admin/assets/js/jquery-2.1.4.min.js"></script>
        <script src="~/Content/bootstrap-3.3.7/js/bootstrap.min.js"></script>
        @*//xxxx代表发布服务端地址*@
        <script src="http://xxxxx/Scripts/jquery.signalR-2.4.1.js"></script>
        <script src="http://xxxxx/signalr/hubs"></script>
    
        <script type="text/javascript">
            var chat;
            $(function () {
         
    
                chat = $.connection.ServerHub;
                $.connection.hub.url = 'http://xxxx/signalr';//xxxx代表发布服务端地址
    
                //开启连接
                $.connection.hub.start({
          jsonp: true }).done(function () {
         
                    //调用Server端的userConnected方法,并传送登录用户名给Server
                    chat.server.userConnected(getUrlParam("id"), "teacher", 0);
    
                });
    
                //接受广播
                chat.client.showMessage = function (message) {
         
    
                    alert(message);
                }
    
                //调用hub中注册的sendMessage 方法
                chat.client.sendMessage = function (roomname, message) {
         
                    $("#messageList").append(message);
                    var height = document.getElementById('messageList');
                    height.scrollTop = height.scrollHeight;
                }
    
    
                //调用hub中注册的获取房间名称方法
                chat.client.getRoomName = function (roomname) {
         
                    $("#send").attr("data-roomname", roomname);
                }
    
    
                //新增上线用户
                chat.client.addList = function (id, name, img) {
         
                    var html = "

    " + name + "

    "
    ; $("#studentlist").append(html); $("#count").html("【" + $("#studentlist p").size() + "】"); } //老师取得自己信息 chat.client.getTeaList = function (userList) { var res = JSON.parse(userList); var html = "" + res.RealName + ""; $("#teacheronly").html(html); $("#teacheronly").attr("data-teacid", res.UserName); } //移除下线用户 chat.client.removeList = function (username) { $("#" + username).remove(); $("#count").html("【" + $("#studentlist p").size() + "】"); } window.onbeforeunload = function () { var roomName = $("#send").data("roomname"); chat.server.exitRoom(roomName); return "您确定退出吗?"; // return 这句必不可少 } //注册查询房间列表的方法 chat.client.getRoomList = function (data) { if (data) { var jsonData = $.parseJSON(data); $("#roomList").html(" "); for (var i = 0; i < jsonData.length; i++) { var html = '
  • 房间名:' + jsonData[i] + '
  • '
    $("#roomList").append(html); } } } //调用hub中addRoom 加入房间的方法 chat.client.addRoom = function (roomName) { var html = '
    + roomName + '" roomname="' + roomName + '" > \ ' + roomName + '房间聊天记录如下:
      ' $("#rooms").append(html); } //发送消息 $("#send").on("click", function () { var val = $("#sendmsg").val(); var roomName = $(this).data("roomname"); //chat.server.sendHtmlMsg(roomName, val); //$("#sendmsg").val(""); if (val.length <= 200) { chat.server.sendHtmlMsg(roomName, val); $("#sendmsg").val(""); } else { $("#messageList").append("
    •  最多发送200字!
    • "
      ); } }); //清屏 $("#clear").on("click", function () { $("#messageList li").remove(); }); //回车发送 $(document).keydown(function (event) { if (event.keyCode == 13) { $("#send").click(); } }) }); //获取url参数 function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r != null) return unescape(r[2]); return null; //返回参数值 } </script> </body> </html>

      源码下载:链接:https://pan.baidu.com/s/1PhwjEIKDji2n_vrHe71A1w
      提取码:7uax

      你可能感兴趣的:(.net即时通信,即时通信,.net)