Hub
public class StreamHub : Hub
{
public ChannelReader<string> ReadLogStream()
{
var channel = Channel.CreateUnbounded<string>();
_ = WriteFileLine(channel.Writer); return channel.Reader;
} private async Task WriteFileLine(ChannelWriter<string> writer)
{
using (var streamReader = new StreamReader(Directory.GetCurrentDirectory() + "/logs/server.log"))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
await writer.WriteAsync(line);
await Task.Delay(TimeSpan.FromSeconds(2));
} writer.TryComplete();
}
}
}
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace SignalRCharSample.Hubs
{
[Authorize]
public class UserChatHub: Hub
{
public async Task SendMessage(string toUserName, string message)
{
await Clients.User(toUserName).SendAsync("ReceiveMessage", $"{DateTime.Now}--{Context.UserIdentifier}--{message}");
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
UserName:<input type="text" id="userInput" />
Message:<input type="text" id="messageInput" />
<input type="button" id="sendButton" value="Send" />
</div>
<ul id="messagesList"></ul>
<script src="http://localhost:57634/lib/jquery/dist/jquery.js"></script>
<script src="http://localhost:57634/lib/signalr.min.js"></script>
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:57634/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = user + " says " + message;
var li = document.createElement("li");
li.textContent = msg;
document.getElementById("messagesList").appendChild(li);
}); connection.start().catch(function (err) {
return console.error(err.toString());
}); document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
}); event.preventDefault();
}); </script>
</body>
</html>
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace SignalRCharSample.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, DateTime.Now + "--" + message);
} public Task SendMessageToCaller(string message)
{
return Clients.Caller.SendAsync("ReceiveMessage",message);
} public Task SendMessageToGroups(string message)
{
List<string> groups = new List<string>() { "Group1","Group2" };
return Clients.Groups(groups).SendAsync("ReceiveMessage", message);
} public override async Task OnConnectedAsync()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "Group1");
await base.OnConnectedAsync();
} public override async Task OnDisconnectedAsync(Exception exception)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "Group1");
await base.OnDisconnectedAsync(exception);
}
}
}
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace SignalRCharSample.Hubs
{
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
//return connection.GetHttpContext().Request.Query["userid"]; return connection.User?.FindFirst("UserName")?.Value;
}
}
}
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace SignalRCharSample.Hubs
{
public class GroupChatHub: Hub
{
public async Task AddToGroup(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName); await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
} public async Task RemoveFromGroup(string groupName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName); await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has left the group {groupName}.");
} public Task SendMessageToGroup(string groupName, string message)
{
return Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId}: {message}");
} public override Task OnConnectedAsync()
{
return base.OnConnectedAsync();
}
}
}
Hub的更多相关文章
- 从爬取湖北某高校hub教务系统课表浅谈Java信息抓取的实现 —— import java.*;
原创文章与源码,如果转载请注明来源. 开发环境:Myeclipse,依赖包:apache-httpclient . Jsoup.base64 一.概述 整个系统用Java开发.我们现在要做的是类似于超 ...
- hub,桥,交换机,路由器的区别
1.四种设备在网络中的物理位置 如下图 2.这四种设备的本质 这四种设备,不管怎样,他们都是进行包的转发,只不过转发的行为有些不一样而已 3.逐一介绍 对于hub,一个包过来后,直接将包转发到其他口. ...
- 把代码搬到Git Hub 吧(一)
作为码农的我们,应该都是知道Git Hub,因为git几乎是码农必备的技能啊,所以就不多介绍Git Hub了,直入主题,这篇博客主要讲解Git Hub网页端和客户端的操作. 网页端: 首页第一步自然是 ...
- SignalR入门之Hub
在持久性连接的基础上,SignalR提供了一个更高层次的抽象层:Hub,基于javascript的灵活性和C#的动态特性,Hub是一个至关重要的开发模式,它消弭了客户端和服务端这两个独立的物理环境之间 ...
- asp.net signalR 专题—— 第四篇 模拟RPC模式的Hub操作
在之前的文章中,我们使用的都是持久连接,但是使用持久连接的话,这种模拟socket的形式使用起来还是很不方便的,比如只有一个唯一的 OnReceived方法来处理业务逻辑,如下图: protected ...
- 配置 Docker 加速器(Docker Hub Mirror)
Docker 加速器是什么,我需要使用吗? 使用 Docker 的时候,需要经常从官方获取镜像,但是由于显而易见的网络原因,拉取镜像的过程非常耗时,严重影响使用 Docker 的体验.因此 DaoCl ...
- hub config
@echo off title Selenium_Hub cd /d %~dp0 java -jar selenium-server-standalone-2.48.2.jar -role hub - ...
- Windows Azure Service Bus Notification Hub推送通知
前言 随着Windows Azure 在中国的正式落地,相信越来越多的人会体验到Windows Azure带来的强大和便利.在上一篇文章中, 我们介绍了如何利用Windows Azure中的Servi ...
- SignalR入门之从外部访问持久性连接或Hub
有的时候,需要从外部访问持久性连接或Hub服务. 比如,假设A和B两个客户端正在聊天,那么系统或第三方在不参与聊天的情况需要为他们发送系统消息,那么此时,就需要独立来访问持久性连接或Hub服务. 之前 ...
- 项目总结笔记系列 Social Hub KT Session2
KT Session2: 主要是代码的实现(KT is knowledge Transfer) 如图所示,在整个Social Hub项目中,我们的项目Data Feed Service处于承上启下的作 ...
随机推荐
- win7电脑休眠后只能按重启键解决办法
一.点击"开始"后选择控制面板 二.选择"电源选项" 三.点击"更改计划设置" 四.选择"更改高级电源设置" 五.点击& ...
- python 搭建自启动FTP服务器,编译后exe后个人随时可用,非常方便
import win32apiimport win32conclass AutoRun: """ itemname:要添加的项值名称 , path:要添加的exe路径绝对 ...
- linux修改ssh默认端口
1 . 登录服务器,打开sshd_config文件 vim /etc/ssh/sshd_config 2 . 找到#Port 22,默认是注释掉的,先把前面的#号去掉,再插入一行设置成你想要的端口号, ...
- el-scrollbar滚动加载
mounted() { 监听滚动条 this.$refs.scrollbar.wrap.addEventListener("scroll", this.scrollCo ...
- 前端记录:树形插件zTree 和 表格扩展 tableX
树形插件zTree 表格扩展 tableX 项目实例 [地区联动实现_前端] <title>区域设置</title> <!--当前位置开始--> <div c ...
- pip设置镜像
国内镜像网站 镜像站名 网址 阿里云开源镜像站 http://mirrors.aliyun.com/ 网易开源镜像站 http://mirrors.163.com/ 搜狐开源镜像 http://mir ...
- ENGG1310 P2.1 Intro to CE Computer Systems, Programming & Networking
课程内容笔记,自用,不涉及任何 assignment,exam 答案 Notes for self-use, do not include any assignments or exams H/W & ...
- 【转载】C++标准库容器与C#容器对比
转载自栈他喵的又溢出了 我简单的整理一下,方便观看: C#容器 C++容器 备注 Array C array .net的Array可以是非0起始索引(鸡肋?查了一下,用Array.CreateInst ...
- Canvas布局下使用附加属性使控件岁鼠标移动
定义附加属性 public class MoveBehavior { public static readonly DependencyProperty IsMoveAbleProperty = De ...
- nodejs查询
const tagModel = require("../mongodb"); 1 const mongoose = require("mongoose"); ...