我想向組發送消息,我無法使其工作。我將用戶添加到組中,但不會發送消息,儘管使用Clients.All可行。這是我的設置。無法發送到SignalR組
Javascript調用連接到集線器,它獲取組中的用戶並將其作爲聊天室中的用戶返回,然後向服務器發送一個連接室,以便我可以將用戶添加到該組中,並將消息從服務器給客戶說明他們已經加入。
Javascript功能來連接
$.connection.hub.start()
.done(function() {
chatHub.server.getConnectedUsers("MyChat") //return user list
.done(function (connectedUsers) {
ko.utils.arrayForEach(connectedUsers, function (item) {
users.contacts.push(new chatR.user(item.Username));
});
}).done(function() {
chatHub.server.joinRoom("MyChat", "My Room")
.done()
.fail(function(){ alert('failed to join group')}); //join the group
});
});
服務器端JoinRoom
public async Task JoinRoom(string room, string displayName)
{
// context variables
var name = Context.User.Identity.Name;
var connectionId = Context.ConnectionId;
// new group
var group = new SignalGroup(room, displayName, SignalGroupType.Chatroom);
// adding relation to storage
_manager.AddGroup(name, group); <-- adds to database
// anouncing the room was joined
Clients.Group(room).joinedRoom(name); //<-- This does not work
//Clients.All.joinedRoom(name); <-- This works
//Clients.OthersInGroup(room).joinedRoom(name);
// add group to SignalR
await Groups.Add(room, connectionId); // <-- why does this have to be last? when I move this before the _manager.AddGroup it never sends the client message?
}
所以Clients.Group(room).joinedRoom(name)
不工作,我沒有得到任何錯誤消息,並在客戶端永遠不會收到該消息。這是客戶端功能。
客戶端JoinedRoom
chatHub.client.joinedRoom = function (name) {
var connectedUser = new chatR.user(name);
users.contacts.push(connectedUser);
chat.messages.push(new chatR.chatMessage("System", name + " joined.", new Date()));
};
對於「獎金」這裏是我的SendChatMessage
方法時,我向所有而不是一組過的作品。
public void SendChatMessage(string room, string message)
{
// context variables
var name = Context.User.Identity.Name;
var user = _manager.GetUser(name);
if (user.IsInGroup(room))
{
// tells clients to addChatMessage
//Clients.All.addChatMessage(name, message, DateTime.Now);
Clients.Group(room).addChatMessage(name, message, DateTime.Now);
}
}
所以我的主要問題是,爲什麼我不能發送到組?我明確地將它們添加到組中並向該組發送消息?
第二個問題是,爲什麼在JoinRoom方法必須有添加到組呼最後還是它似乎它不與所有的工作都什?
如果您有這東西,這將是偉大的,以及任何有用的鏈接,我看了所有的MS文檔和幾個教程這讓我連上這是爲什麼不工作更加困惑。
編輯:我在joinRoom調用中添加了一個失敗檢查,看看我是否收回任何東西,看起來好像SignalR無法加入組本身。我不知道我會如何解決這個問題。
Doh,今晚我會回家看看這個。我希望就是這樣,很有道理。謝謝:) – Tony
是的,我一定已經想通了,因爲我現在在我的代碼中已經這樣了。偷偷摸摸地交換了params哈哈。謝謝!! – Tony