32 messaggi dal 13 agosto 2017
Buonasera amici, sto implementando una chat tramite la libreria Signalr. Ho impostato il codice funzionante che invia i messaggi a tutti gli utenti connessi ed è il seguente:

Parte server:

'MessageDetail.vb':
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web

Namespace SignalRChat.Common
    Public Class MessageDetail

        Public Property UserName() As String
            Get
                Return m_UserName
            End Get
            Set(value As String)
                m_UserName = Value
            End Set
        End Property
        Private m_UserName As String

        Public Property Message() As String
            Get
                Return m_Message
            End Get
            Set(value As String)
                m_Message = Value
            End Set
        End Property
        Private m_Message As String

    End Class
End Namespace


'UserDetail.vb':
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web

Namespace SignalRChat.Common
    Public Class UserDetail
        Public Property ConnectionId() As String
            Get
                Return m_ConnectionId
            End Get
            Set(value As String)
                m_ConnectionId = Value
            End Set
        End Property
        Private m_ConnectionId As String
        Public Property UserName() As String
            Get
                Return m_UserName
            End Get
            Set(value As String)
                m_UserName = Value
            End Set
        End Property
        Private m_UserName As String
    End Class
End Namespace


'ChatHub.vb'
Imports Microsoft.AspNet.SignalR
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports Chatproject.SignalRChat.Common
Imports System.Threading.Tasks
Imports Microsoft.Owin
Imports Owin

Namespace Chatproject
    Public Class ChatHub
        Inherits Hub
#Region "Data Members"

        Shared ConnectedUsers As New List(Of UserDetail)()
        Shared CurrentMessage As New List(Of MessageDetail)()

#End Region

#Region "Methods"

        Public Sub Connect(userName As String)
            Dim id = Context.ConnectionId


            If ConnectedUsers.Where(Function(x) x.ConnectionId = id).Count = 0 Then
                ConnectedUsers.Add(New UserDetail() With { _
                    .ConnectionId = id, _
                    .UserName = userName _
                })

                ' send to caller
                Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage)

                ' send to all except caller client

                Clients.AllExcept(id).onNewUserConnected(id, userName)
            End If

        End Sub

        Public Sub SendMessageToAll(userName As String, message As String)
            ' store last 100 messages in cache
            AddMessageinCache(userName, message)

            ' Broad cast message
            Clients.All.messageReceived(userName, message)
        End Sub

        Public Sub SendPrivateMessage(toUserId As String, message As String)

            Dim fromUserId As String = Context.ConnectionId

            Dim toUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = toUserId)
            Dim fromUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = fromUserId)

            If toUser IsNot Nothing AndAlso fromUser IsNot Nothing Then
                ' send to 
                Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message)

                ' send to caller user
                Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message)
            End If

        End Sub

        Public Overrides Function OnDisconnected(stopCalled As Boolean) As Threading.Tasks.Task

            Dim item = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = Context.ConnectionId)
            If item IsNot Nothing Then
                ConnectedUsers.Remove(item)
                Dim id = Context.ConnectionId

                Clients.All.onUserDisconnected(id, item.UserName)
            End If

            Return MyBase.OnDisconnected(stopCalled)
        End Function



#End Region

#Region "private Messages"

        Private Sub AddMessageinCache(userName As String, message As String)
            CurrentMessage.Add(New MessageDetail() With { _
                .UserName = userName, _
                .Message = message _
            })

            If CurrentMessage.Count > 100 Then
                CurrentMessage.RemoveAt(0)
            End If
        End Sub

#End Region
    End Class

End Namespace


Parte client:

  <script type="text/javascript">

             $(function () {

                 setScreen(false);

                 // Declare a proxy to reference the hub. 
                 var chatHub = $.connection.chatHub;

                 registerClientMethods(chatHub);

                 // Start Hub
                 $.connection.hub.start().done(function () {

                     registerEvents(chatHub)

                 });

             });

             function setScreen(isLogin) {

                 if (!isLogin) {

                     $("#divChat").hide();
                     $("#divLogin").show();
                 }
                 else {

                     $("#divChat").show();
                     $("#divLogin").hide();
                 }

             }

             function registerEvents(chatHub) {
  
                 $("#btnStartChat").click(function () {
                     var name = document.getElementById('<%=LoginName1.ClientID%>').innerHTML;

                     if (name.length > 0) {
                         chatHub.server.connect(name);
                     }
                     else {
                         alert("Please enter name");
                     }

                 });


                 $('#btnSendMsg').click(function () {

                     var msg = $("#txtMessage").val();
                     if (msg.length > 0) {

                         var userName = $('#hdUserName').val();
                         chatHub.server.sendMessageToAll(userName, msg);
                         $("#txtMessage").val('');
                     }
                 });


                 $("#txtNickName").keypress(function (e) {
                     if (e.which == 13) {
                         $("#btnStartChat").click();
                     }
                 });

                 $("#txtMessage").keypress(function (e) {
                     if (e.which == 13) {
                         $('#btnSendMsg').click();
                     }
                 });


             }

             function registerClientMethods(chatHub) {

                 // Calls when user successfully logged in
                 chatHub.client.onConnected = function (id, userName, allUsers, messages) {

                     setScreen(true);

                     $('#hdId').val(id);
                     $('#hdUserName').val(userName);
                     $('#spanUser').html(userName);

                     // Add All Users
                     for (i = 0; i < allUsers.length; i++) {

                         AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
                     }

                     // Add Existing Messages
                     for (i = 0; i < messages.length; i++) {

                         AddMessage(messages[i].UserName, messages[i].Message);
                     }


                 }

                 // On New User Connected
                 chatHub.client.onNewUserConnected = function (id, name) {

                     AddUser(chatHub, id, name);
                 }


                 // On User Disconnected
                 chatHub.client.onUserDisconnected = function (id, userName) {

                     $('#' + id).remove();

                     var ctrId = 'private_' + id;
                     $('#' + ctrId).remove();


                     var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');

                     $(disc).hide();
                     $('#divusers').prepend(disc);
                     $(disc).fadeIn(200).delay(2000).fadeOut(200);

                 }

                 chatHub.client.messageReceived = function (userName, message) {

                     AddMessage(userName, message);
                 }


                 chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {

                     var ctrId = 'private_' + windowId;


                     if ($('#' + ctrId).length == 0) {

                         createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);

                     }

                     $('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');

                     // set scrollbar
                     var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
                     $('#' + ctrId).find('#divMessage').scrollTop(height);

                 }

             }

             function AddUser(chatHub, id, name) {

                 var userId = $('#hdId').val();

                 var code = "";

                 if (userId == id) {

                     code = $('<div class="loginUser">' + '<ul class="users-list clearfix">' + '<li>' + '<img src="Avatar/A01.png"/>' + name + '</a>' + '<span class="users-list-date">' + '</span>' + '</li>' + '</ul>' + "</div>");

                 }
                 else {

                     code = $('<a id="' + id + '" class="user" >' + '<ul class="users-list clearfix">' + '<li>' + '<img src="Avatar/A01.png"/>' + name + '<span class="users-list-date">' + '</span>' + '</li>' + '</ul>' + '</a>');

                     $(code).dblclick(function () {

                         var id = $(this).attr('id');

                         if (userId != id)
                             OpenPrivateChatWindow(chatHub, id, name);

                     });
                 }


                 $("#divusers").append(code);

             }

             function AddMessage(userName, message) {
                 var data = new Date();
                 var mese = data.getMonth() + 1;
                 if (mese < 10) {
                     mese = '0' + mese;
                 } else {
                     mese = mese + '';
                 }
                 var giorno = data.getDate();
                 if (giorno < 10) {
                     giorno = '0' + giorno;
                 } else {
                     giorno = giorno + '';
                 }
                 var anno = data.getFullYear();
                 var ora = data.getHours();
                 if (ora < 10) {
                     ora = '0' + ora;
                 } else {
                     ora = ora + '';
                 }
                 var minuti = data.getMinutes();
                 if (minuti < 10) {
                     minuti = '0' + minuti;
                 } else {
                     minuti = minuti + '';
                 }
                 var oggi = giorno + "/" + mese + "/" + anno + " " + ora + ":" + minuti;

                 $('#divChatWindow').append('<div class="direct-chat-msg">' + '<div class="direct-chat-info clearfix">' + '<span class="direct-chat-name pull-left">' + userName + '</span>' + '<span class="direct-chat-timestamp pull-right">' + oggi + '</span>' + '</div>' + '<img class="direct-chat-img" src="Avatar/A01.png" alt="message user image" />' + '<div class="direct-chat-text">' + message + '</div>' + '</div>');


             function OpenPrivateChatWindow(chatHub, id, userName) {

                 var ctrId = 'private_' + id;

                 if ($('#' + ctrId).length > 0) return;

                 createPrivateChatWindow(chatHub, id, ctrId, userName);

             }

             function createPrivateChatWindow(chatHub, userId, ctrId, userName) {

                 var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
                            '<div class="header">' +
                               '<div  style="float:right;">' +
                                   '<img id="imgDelete"  style="cursor:pointer;" src="/Images/delete.png"/>' +
                                '</div>' +

                                '<span class="selText" rel="0">' + userName + '</span>' +
                            '</div>' +
                            '<div id="divMessage" class="messageArea">' +

                            '</div>' +
                            '<div class="buttonBar">' +
                               '<input id="txtPrivateMessage" class="msgText" type="text"   />' +
                               '<input id="btnSendMessage" class="submitButton button" type="button" value="Send"   />' +
                            '</div>' +
                         '</div>';

                 var $div = $(div);

                 // DELETE BUTTON IMAGE
                 $div.find('#imgDelete').click(function () {
                     $('#' + ctrId).remove();
                 });

                 // Send Button event
                 $div.find("#btnSendMessage").click(function () {

                     $textBox = $div.find("#txtPrivateMessage");
                     var msg = $textBox.val();
                     if (msg.length > 0) {

                         chatHub.server.sendPrivateMessage(userId, msg);
                         $textBox.val('');
                     }
                 });

                 // Text Box event
                 $div.find("#txtPrivateMessage").keypress(function (e) {
                     if (e.which == 13) {
                         $div.find("#btnSendMessage").click();
                     }
                 });

                 AddDivToContainer($div);

             }

             function AddDivToContainer($div) {
                 $('#divContainer').prepend($div);

                 $div.draggable({

                     handle: ".header",
                     stop: function () {

                     }
                 });

                 ////$div.resizable({
                 ////    stop: function () {

                 ////    }
                 ////});

             }
             }
    </script>


Ora se mi collego alla stanza n°1, nel momento in cui invio il messaggio devono riceverlo soltanto gli utenti connessi alla stanza n°1 e il codice server di 'ChatHub.vb' dovrebbe diventare il seguente:
Imports Microsoft.AspNet.SignalR
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports Chatproject.SignalRChat.Common
Imports System.Threading.Tasks
Imports Microsoft.Owin
Imports Owin

Namespace Chatproject
    Public Class ChatHub
        Inherits Hub
#Region "Data Members"

        Shared ConnectedUsers As New List(Of UserDetail)()
        Shared CurrentMessage As New List(Of MessageDetail)()

#End Region

#Region "Methods"

        Public Sub Connect(userName As String)
            Dim id = Context.ConnectionId


            If ConnectedUsers.Where(Function(x) x.ConnectionId = id).Count = 0 Then
                ConnectedUsers.Add(New UserDetail() With { _
                    .ConnectionId = id, _
                    .UserName = userName _
                })

                ' send to caller
                Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage)

                ' send to all except caller client

                Clients.AllExcept(id).onNewUserConnected(id, userName)
            End If

        End Sub
        Public Shared ogroup As String

        Public Sub SendMessageToAll(userName As String, message As String)

            ' store last 100 messages in cache
            AddMessageinCache(userName, message)

            ' Broad cast message
            Clients.Group(ogroup).messageReceived(userName, message)
        End Sub
        Public Sub Join(groupName As String)

            'Dim ogroup As String = Session("ChatOrgid")
            Groups.Add(Context.ConnectionId, ogroup)

        End Sub
        Public Sub SendPrivateMessage(toUserId As String, message As String)

            Dim fromUserId As String = Context.ConnectionId

            Dim toUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = toUserId)
            Dim fromUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = fromUserId)

            If toUser IsNot Nothing AndAlso fromUser IsNot Nothing Then
                ' send to 
                Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message)

                ' send to caller user
                Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message)
            End If

        End Sub

        Public Overrides Function OnDisconnected(stopCalled As Boolean) As Threading.Tasks.Task

            Dim item = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = Context.ConnectionId)
            If item IsNot Nothing Then
                ConnectedUsers.Remove(item)
                Dim id = Context.ConnectionId

                Clients.All.onUserDisconnected(id, item.UserName)
            End If

            Return MyBase.OnDisconnected(stopCalled)
        End Function



#End Region

#Region "private Messages"

        Private Sub AddMessageinCache(userName As String, message As String)
            CurrentMessage.Add(New MessageDetail() With { _
                .UserName = userName, _
                .Message = message _
            })

            If CurrentMessage.Count > 100 Then
                CurrentMessage.RemoveAt(0)
            End If
        End Sub

#End Region
    End Class

End Namespace


Mentre per la parte client non riesco a comprendere come effettuare la connessione, ho provato così ma non funge:

 $(function () {

                 setScreen(false);

                 // Declare a proxy to reference the hub. 
                 var chatHub = $.connection.chatHub;

                 registerClientMethods(chatHub);

                 // Start Hub
                 $.connection.hub.start().done(function () {
                         hub.join("Room A");

                     registerEvents(chatHub)

                 });

             });


Ora il punto è: la parte server così modificata è corretta? Se si come potrei fare per implementare la connessione lato client?
Grazie a tutti un saluto.
32 messaggi dal 13 agosto 2017
Dunque guardando anche su questo forum ho notato che ci sono esempi al riguardo ed modificato il codice lato server così:

Imports Microsoft.AspNet.SignalR
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports Chatproject.SignalRChat.Common
Imports System.Threading.Tasks
Imports Microsoft.Owin
Imports Owin

Namespace Chatproject
    Public Class ChatHub
        Inherits Hub
#Region "Data Members"

        Shared ConnectedUsers As New List(Of UserDetail)()
        Shared CurrentMessage As New List(Of MessageDetail)()

#End Region

#Region "Methods"

        Public Sub Connect(userName As String)
            Dim id = Context.ConnectionId


            If ConnectedUsers.Where(Function(x) x.ConnectionId = id).Count = 0 Then
                ConnectedUsers.Add(New UserDetail() With { _
                    .ConnectionId = id, _
                    .UserName = userName _
                })


                ' send to caller
                Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage)

                ' send to all except caller client

                Clients.AllExcept(id).onNewUserConnected(id, userName)
            End If

        End Sub
        Public Sub JoinGroup(ByVal groupName As String)
            Groups.Add(Context.ConnectionId, groupName)
        End Sub

        Public Sub SendToGroup(ByVal message As String, ByVal groupName As String)

            Clients.Group(groupName).ReceiveMessage(message)

        End Sub
        Public Sub SendMessageToAll(userName As String, message As String)
            ' store last 100 messages in cache
            AddMessageinCache(userName, message)

            ' Broad cast message
            Clients.All.messageReceived(userName, message)
        End Sub

        Public Sub SendPrivateMessage(toUserId As String, message As String)

            Dim fromUserId As String = Context.ConnectionId

            Dim toUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = toUserId)
            Dim fromUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = fromUserId)

            If toUser IsNot Nothing AndAlso fromUser IsNot Nothing Then
                ' send to 
                Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message)

                ' send to caller user
                Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message)
            End If

        End Sub

        Public Overrides Function OnDisconnected(stopCalled As Boolean) As Threading.Tasks.Task

            Dim item = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = Context.ConnectionId)
            If item IsNot Nothing Then
                ConnectedUsers.Remove(item)
                Dim id = Context.ConnectionId

                Clients.All.onUserDisconnected(id, item.UserName)
            End If

            Return MyBase.OnDisconnected(stopCalled)
        End Function



#End Region

#Region "private Messages"

        Private Sub AddMessageinCache(userName As String, message As String)
            CurrentMessage.Add(New MessageDetail() With { _
                .UserName = userName, _
                .Message = message _
            })

            If CurrentMessage.Count > 100 Then
                CurrentMessage.RemoveAt(0)
            End If
        End Sub

#End Region
    End Class

End Namespace


Per quanto riguarda il lato client in questa funzione però non mi invia nessun messaggio:


 function registerEvents(chatHub) {
  
                 $("#btnStartChat").click(function () {
                     $.connection.chatHub.server.joinGroup("Nuoto");

                     var name = document.getElementById('<%=LoginName1.ClientID%>').innerHTML;

                     if (name.length > 0) {

                         chatHub.server.connect(name);

                     }
                     else {
                         alert("Please enter name");
                     }

                 });


                 $('#btnSendMsg').click(function () {
                     var msg = $("#txtMessage").val();
                     if (msg.length > 0) {

                         var userName = $('#hdUserName').val();

                         chatHub.server.SendToGroup(userName, msg);


                         $("#txtMessage").val('');
                     }
                 });


Dove sbaglio?
Modificato da MarkRoss il 21 gennaio 2018 00.14 -
11.097 messaggi dal 09 febbraio 2002
Contributi
Ciao,
vedo che, lato client, invochi la funzione SendToGroup così, fornendo username e messaggio.
chatHub.server.SendToGroup(userName, msg);


Invece, lato server, il metodo si aspetta il messaggio e il nome del gruppo.
Public Sub SendToGroup(ByVal message As String, ByVal groupName As String)


Quindi credo che ci sia incoerenza nei parametri forniti. Non so dirti se ci sono altre cose da modificare. Casomai dovresti fornire un progetto di esempio in modo che si possa verificare velocemente cosa c'è che non va.
Eventualmente controlla se ci sono errori nella console del browser (aprila con il tasto F12).

Nel frattempo ti mando un'applicazione funzionante che ho scritto in VB.NET, vedi se riesci a prendere spunto da lì. Io per la presentazione dei dati lato client uso KnockoutJS, in modo che il codice resti leggibile.
https://github.com/BrightSoul/aspnet-signalr-groups-demo

ciao,
Moreno

Enjoy learning and just keep making

Torna al forum | Feed RSS

ASPItalia.com non è responsabile per il contenuto dei messaggi presenti su questo servizio, non avendo nessun controllo sui messaggi postati nei propri forum, che rappresentano l'espressione del pensiero degli autori.