C# SignalR .Net 客户端:如何向组发送消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16167735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SignalR .Net client: How do I send a message to a Group?
提问by robrtc
I am using the sample Chat application from the SignalR Wiki Getting Started Hubs page. I have extended it to add Group support and it is working fine.
我正在使用 SignalR Wiki Getting Started Hubs 页面中的示例聊天应用程序。我已将其扩展为添加组支持,并且工作正常。
However, now I want to send a message to the group from an external Console application. Here is my code for the Console app and below that my code for Groups. How do I send a message to a Group from a proxy? Is it possible?
但是,现在我想从外部控制台应用程序向组发送消息。这是我的控制台应用程序代码,下面是我的组代码。如何从代理向群组发送消息?是否可以?
// Console App
using System;
using Microsoft.AspNet.SignalR.Client.Hubs;
namespace SignalrNetClient
{
class Program
{
static void Main(string[] args)
{
// Connect to the service
var connection = new HubConnection("http://localhost:50116");
var chatHub = connection.CreateHubProxy("Chat");
// Print the message when it comes in
connection.Received += data => Console.WriteLine(data);
// Start the connection
connection.Start().Wait();
chatHub.Invoke("Send", "Hey there!");
string line = null;
while ((line = Console.ReadLine()) != null)
{
// Send a message to the server
connection.Send(line).Wait();
}
}
}
}
SignalR Web App Host:
SignalR Web 应用程序主机:
namespace SignalrServer.Hubs
{
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.All.addMessage(message);
Clients.Group("RoomA").addMessage("Group Message " + message);
}
//server
public void Join(string groupName)
{
Groups.Add(Context.ConnectionId, groupName);
}
}
}
Default.aspx
默认.aspx
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.1.min.js" type="text/javascript"></script>
<!-- If this is an MVC project then use the following -->
<!-- <script src="~/signalr/hubs" type="text/javascript"></script> -->
<script src="signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
$.connection.hub.start(function () {
chat.server.join("RoomA");
});
// Start the connection
$.connection.hub.start().done(function () {
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val());
});
});
});
</script>
<div>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages">
</ul>
</div>
采纳答案by Tim B James
What I have done with something similar is to create a method which accepts an object of your choice, e.g.
我对类似的事情所做的是创建一个接受您选择的对象的方法,例如
Your new class
你的新班级
public class MyMessage{
public string Msg { get; set; }
public string Group { get; set; }
}
Then create a method in the Hub that accepts this object.
然后在 Hub 中创建一个接受这个对象的方法。
public void Send(MyMessage message)
{
// Call the addMessage method on all clients
Clients.All.addMessage(message.Msg);
Clients.Group(message.Group).addMessage("Group Message " + message.Msg);
}
Then from your client, you can then pass this object in.
然后从你的客户端,你可以传入这个对象。
chatHub.Invoke<MyMessage>("send", new MyMessage() { Msg = "Hello World", Group = "RoomA" });
You can then also call this from the JS client
然后你也可以从 JS 客户端调用它
chat.server.send({ Msg: "Hello World", Group: "RoomA" });
回答by Tony
In Winform .Net framework 4.0the group doesn't work any more.
在Winform .Net framework 4.0组中不再工作。
Server Code:
服务器代码:
[HubName("PublicHub")]
public class PublicHub : HubBase
{
/// <summary>
/// join group
/// </summary>
/// <param name="userLoginName"></param>
/// <param name="hotelId"></param>
/// <param name="groupCode"></param>
[HubMethodName("JoinGroup")]
public async Task JoinGroupAsync(string userLoginName, string hotelId, string groupCode)
{
await Groups.Add(Context.ConnectionId, ShopGroupKey(hotelId, groupCode));
Clients.Group(ShopGroupKey(hotelId, groupCode)).UpdateRoomStatus("UpdateRoomStatus", "UpdateRoomStatus");
}
/// <summary>
///
/// </summary>
/// <param name="userLoginName"></param>
/// <param name="hotelId"></param>
/// <param name="groupCode"></param>
[HubMethodName("QuitGroup")]
public async Task QuitGroupAsync(string userLoginName, string hotelId, string groupCode)
{
await Groups.Remove(Context.ConnectionId, ShopGroupKey(hotelId, groupCode));
}
}
Client Code:
客户代码:
internal IHubProxy PublicHub;
internal IHubProxy RoomHub;
public static SignalRUtility Instance
{
get
{
if (_instance == null)
{
Host = ConfigurationManager.AppSettings["signalRHost"];
_instance = new SignalRUtility();
}
return _instance;
}
}
private SignalRUtility()
{
Connection = new HubConnection(Host + "/signalr", useDefaultUrl: false);
PublicHub = Connection.CreateHubProxy("PublicHub");
RoomHub = Connection.CreateHubProxy("RoomStatusHub");
RoomHub.On<string>("UpdateRoomStatus", (code) =>
{
if(RoomStatusDelegates != null)
{
RoomStatusDelegates(code);
}
});
RoomHub.On<string>("UpdateOrderStatus", (code) =>
{
if (OrderStatusDelegates != null)
{
OrderStatusDelegates(code);
}
});
Connection.Start().Wait();
}
Doesn't receive any message from the server side in client side.
Client.Allcan send message.
在客户端不接收来自服务器端的任何消息。
Client.All可以发消息。

