我正在使用來自SignalR Wiki入門中心頁面的示例聊天應用程序。我已經擴展它來添加組支持,它工作正常。SignalR .Net客戶端:如何向羣組發送消息?
但是,現在我想從外部控制檯應用程序向組發送消息。這裏是我的控制檯應用程序的代碼,下面是我的組代碼。我如何從代理向組發送消息?可能嗎?
// 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應用主機:
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的
<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>
我想你知道這個名字在發送消息之前的組? – 2013-04-23 11:55:17
是的,我有組名。 – robrtc 2013-04-23 12:24:18
現在我將組名與消息結合起來,然後在發送方法內拆分字符串。但是,我很好奇,如果有一個更優雅的解決方案。 – robrtc 2013-04-23 12:59:03