netty消息推送系统_聊天服务器

netty消息推送系统_聊天服务器简易聊天室转:忘了…以下为自动创建代理hub方式使用NuGet引用:Microsoft.AspNet.SignalR什么时候使用generatedproxy如果你要给客户端的方法注册多

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

 简易聊天室转:忘了…

以下为自动创建代理hub方式

使用NuGet引用:Microsoft.AspNet.SignalR

什么时候使用 generated proxy
如果你要给客户端的方法注册多个事件处理器,那么你就不能使用 generated proxy。如果你不使用 generated proxy ,那么你就不能引用 "signalr/hubs" URL。

 

客户端设置
首先需要引用jQuery,SignalR,signalr/hubs
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
<script src="signalr/hubs"></script>
 

如何引用动态的 generated proxy
ASP.NET MVC 4 or 5 Razor 

<script src="~/signalr/hubs"></script>
ASP.NET MVC 3 Razor 

<script src="@Url.Content("~/signalr/hubs")"></script>
ASP.NET Web Forms 

<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
/signalr/hubs 是 SignalR 自动生成的,当你启动调试的时候会在Script Documents 看到它

=====================================以下为例子===============================================

1、右键=》添加项目=》OWIN Startup class=》Startup.cs

添加Startup类

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Demo_SignalR_2._4._0.Models.Startup))]

namespace Demo_SignalR_2._4._0.Models
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();
        }
    }
}

2、右键=》新建项目=》SignalR Hub Class (v2)=》ChatHub.cs

添加ChatHub类

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace Demo_SignalR_2._4._0.Models
{
    [HubName("chat")]
    public class ChatHub : Hub
    {
        public static ConcurrentDictionary<string, string> OnLineUsers = new ConcurrentDictionary<string, string>();

        [HubMethodName("send")]
        public void Send(string message)
        {
            string clientName = OnLineUsers[Context.ConnectionId];
            message = HttpUtility.HtmlEncode(message).Replace("\r\n", "<br/>").Replace("\n", "<br/>");
            Clients.All.receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), clientName, message);
        }

        [HubMethodName("sendOne")]
        public void Send(string toUserId, string message)
        {
            string clientName = OnLineUsers[Context.ConnectionId];
            message = HttpUtility.HtmlEncode(message).Replace("\r\n", "<br/>").Replace("\n", "<br/>");
            Clients.Caller.receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("您对 {1}", clientName, OnLineUsers[toUserId]), message);
            Clients.Client(toUserId).receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 对您", clientName), message);
        }
        /// <summary>
        /// 服务器接口推送
        /// </summary>
        /// <param name="message"></param>
        public static void ServerPush(string message)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.ServerPush(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message);
        }

        public override System.Threading.Tasks.Task OnConnected()
        {
            string clientName = Context.QueryString["clientName"].ToString();
            OnLineUsers.AddOrUpdate(Context.ConnectionId, clientName, (key, value) => clientName);
            Clients.All.userChange(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 加入了。", clientName), OnLineUsers.ToArray());
            return base.OnConnected();
        }

        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
        {
            string clientName = Context.QueryString["clientName"].ToString();
            Clients.All.userChange(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 离开了。", clientName), OnLineUsers.ToArray());
            OnLineUsers.TryRemove(Context.ConnectionId, out clientName);
            return base.OnDisconnected(stopCalled);
        }

    }
}

例子:聊天室

创建Index.aspx页

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script src="Scripts/jquery.signalR-2.4.0.min.js"></script>
  //这个很重要 <script src="signalr/hubs" type="text/javascript"></script> <style type="text/css"> #chatbox { width: 100%; height: 500px; border: 2px solid blue; padding: 5px; margin: 5px 0px; overflow-x: hidden; overflow-y: auto; } .linfo { } .rinfo { text-align: right; } </style> <script type="text/javascript"> $(function () { var clientName = $("#clientname").val(); var eChatBox = $("#chatbox"); var eUsers = $("#users"); var chat = $.connection.chat; $.connection.hub.qs = { "clientName": clientName }; chat.state.test = "test"; //聊天 chat.client.receiveMessage = function (dt, cn, msg) { console.log(dt); console.log(cn); console.log(msg); var clsName = "linfo"; if (cn == clientName || cn.indexOf("您对") >= 0) clsName = "rinfo"; eChatBox.append("<p class='" + clsName + "'>" + dt + " <strong>" + cn + "</strong> 说:<br/>" + msg + "</p>"); eChatBox.scrollTop(eChatBox[0].scrollHeight); } //更新下拉 chat.client.userChange = function (dt, msg, users) { eChatBox.append("<p>" + dt + " " + msg + "</p>"); eUsers.find("option[value!='']").remove(); for (var i = 0; i < users.length; i++) { if (users[i].Value == clientName) continue; eUsers.append("<option value='" + users[i].Key + "'>" + users[i].Value + "</option>") } } //服务器推送 chat.client.ServerPush = function (dt, msg) { eChatBox.append("<p>" + dt + " " + msg + "</p>"); eChatBox.scrollTop(eChatBox[0].scrollHeight); } $.connection.hub.start().done(function () { $("#btnSend").click(function () { var toUserId = eUsers.val(); if (toUserId != "") { chat.server.sendOne(toUserId, $("#message").val()) .done(function () { //alert("发送成功!"); $("#message").val("").focus(); }) .fail(function (e) { alert(e); $("#message").focus(); }); } else { chat.server.send($("#message").val()) .done(function () { //alert("发送成功!"); $("#message").val("").focus(); }) .fail(function (e) { alert(e); $("#message").focus(); }); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <h3>大众聊天室</h3> <div id="chatbox"> </div> <div> <span>聊天名称:</span> <asp:TextBox ID="clientname" runat="server" ReadOnly="true" style="width:300px;" ></asp:TextBox> <span>聊天对象:</span> <select id="users" name="names"> <% foreach (var item in OnLineUsers) {%> <option value="<%= item.Value %>"><%= item.Text %></option> <%} %> </select> </div> <div> <textarea id="message" name="message" rows="5" style="width: 50%;"></textarea> <input type="button" value="发送消息" id="btnSend" /> </div> </form> </body> </html>

Index.cs

using Demo_SignalR_2._4._0.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo_SignalR_2._4._0
{
    public partial class Index : System.Web.UI.Page
    {
        public List<SelectListItem> OnLineUsers = new List<SelectListItem>();
        protected void Page_Load(object sender, EventArgs e)
        {            
            if (!IsPostBack)
            {   
                clientname.Text = "聊客-" + Guid.NewGuid();
                this.Title = clientname.Text;
            }
            var onLineUserList = ChatHub.OnLineUsers.Select(u => new SelectListItem() { Text = u.Value, Value = u.Key }).ToList();
            onLineUserList.Insert(0, new SelectListItem() { Text = "-所有人-", Value = "" });
            OnLineUsers = onLineUserList;
        }
    }

    public class SelectListItem
    {
        public string Text { get; set; }
        public string Value { get; set; }
    }
}

 

服务器推送:页面 ToServer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo_SignalR_2._4._0
{
    public partial class ToServer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string msg = Request["msg"];
            if (!string.IsNullOrWhiteSpace(msg))
            {
                Models.ChatHub.ServerPush("服务器端推送接口:" + msg);
            }
        }
    }
}

 

Index.aspx 为简易聊天室    ToServer.aspx 为服务器端接口

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/167001.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 【转载】一致性哈希算法(consistent hashing)

    【转载】一致性哈希算法(consistent hashing)

    2021年11月20日
    38
  • css自动换行属性与保留空白属性冲突_css换行样式

    css自动换行属性与保留空白属性冲突_css换行样式word-break属性规定自动换行的处理方法。提示:通过使用word-break属性,可以让浏览器实现在任意位置的换行。所有主流浏览器都支持word-break属性。语法:word-break:normal|break-all|keep-all;normal使用浏览器默认的换行规则。break-all允许在单词内换行。keep-all只能在半角空格或连字符处换行。word-break:break-all所有的都换行,右侧换行没有空隙。word-wrap属性允许

    2025年6月27日
    0
  • 使用xsync脚本分发「建议收藏」

    使用xsync脚本分发「建议收藏」为什么使用xsync脚本来分发文件因为操作简单,只需要执行脚本在后面加上需要分发的文件就行了然后底层不一致,scp使用的是安全拷贝,而xsync使用的是增量拷贝由于底层不一致,xsync比scp快上许多使用脚本来分发文件之前不同节点之间的免密登录安排上脚本实现#!/bin/bash#1输入参数个数,如果没有参数就会退出pcount=$#if((pcount==0));thenechonoargs;exit;fi#2需要分发的文件名称p1=$1fname=`

    2022年5月18日
    51
  • pycharm报错:Process finished with exit code -1073741819 (0xC0000005)

    pycharm报错:Process finished with exit code -1073741819 (0xC0000005)这个错误是真的奇怪,网上说法居然各个都不一样,而我解决的方法也都和大家不一样。所以如果你遇到了这个问题,可以从以下几个方面找找原因,希望能帮到你。我觉得最有可能的是第六种,可以直接看第六种方法。。第一种:读取csv文件如果你读取了csv文件,请参考这个,否则直接跳过原地址:https://stackoverflow.com/questions/28447567/python-termi…

    2022年8月28日
    0
  • pandas中的loc和iloc_pandas loc函数

    pandas中的loc和iloc_pandas loc函数pandas中索引的使用定义一个pandas的DataFrame对像importpandasaspddata=pd.DataFrame({‘A’:[1,2,3],’B’:[4,5,6],’C’:[7,8,9]},index=[“a”,”b”,”c”])dataABCa147b258c3691…

    2022年9月25日
    0
  • cubieboard mysql_Cubieboard开发笔记[通俗易懂]

    cubieboard mysql_Cubieboard开发笔记[通俗易懂]原创作品,转载请注明出处,谢谢!写在前面:亲测可用的搭建流程,但是此流程是针对32位系统的,如果您是64位系统,请勿采用本博文的方式。我搭这个环境居然折腾了一周时间,本来用32位系统好好的,但是官网非要推荐我用64位系统。因为最终打包必须在64位环境下实现。于是乎我一直在不断换系统版本,希望能按照对方工程师所描述的状况来实现,但是我将Error发给他时,他也无计可施。因而还是回到最熟悉的方式进行编…

    2022年7月22日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号