SignalR .Net客户端:如何向组发送消息?

时间:2013-04-23 11:05:36

标签: c# asp.net signalr

我正在使用SignalR Wiki入门中心页面中的示例聊天应用程序。我已经扩展它以添加组支持,它工作正常。

但是,现在我想从外部控制台应用程序向该组发送消息。这是我的控制台应用程序的代码,下面是我的代码组。如何从代理向组发送消息?有可能吗?

// 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主机:

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>

2 个答案:

答案 0 :(得分:29)

我用类似的东西做的是创建一个接受你选择的对象的方法,例如

你的新班级

public class MyMessage{
    public string Msg { get; set; }
    public string Group { get; set; }
}

然后在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);
}

然后,从您的客户端,您可以传入此对象。

chatHub.Invoke<MyMessage>("send", new MyMessage() { Msg = "Hello World", Group = "RoomA" });

然后您也可以从JS客户端

调用它
chat.server.send({ Msg: "Hello World", Group: "RoomA" });

答案 1 :(得分:0)

在Winform .Net framework 4.0中,该组不再起作用。

服务器代码:

[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));
    }
}

和客户代码:

内部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();
    }

在客户端未收到来自服务器端的任何消息。 Client.All可以发送消息。