Search code examples
javascriptc#jquerymodel-view-controllersignalr

how to send a javascript Object from one Client to Another by SignalR


I am working on a Javascript multiplayer game and I need to send a Javascript object from one client to another client using signalR. Till now I am sending client to client data by string or array.
But I don't know how to receive Javascript object in server for sending that object to another client.

var MyInfo = {
    UserName: loginUserName,
    userid: logInUserId,
    getinfo: function() {
        return this.UserName + ' ' + this.userid;
    }
}

Which data type shall I use to receive that Javascript data in my hub.
I am working on C# .NET MVC.


Solution

  • I got the answer of my problem...
    C# language provides automatically conversion of Javascript object to Object data type. Thus I send the Javascript object to server and then receive that object in Object datatype. After that I send that object to destination client, as follow:

    var MyInfo = {
        UserName: loginUserName,
        userid: logInUserId,
        getinfo: function() {
            return this.UserName + ' ' + this.userid;
        }
    };
    
    var MyInfo2 = {
        UserName: "",
        userid: "",
        getinfo: function() {
            return this.UserName + ' ' + this.userid;
        }
    };
    
    var chessR = $.connection.gameHub;
    var myConnectionID;
    chessR.client.testObject = function(temp) {
        MyInfo2.UserName = temp.UserName;
        MyInfo2.userid = temp.userid;
        alert(MyInfo2.getinfo());
    }
    $.connection.hub.start().done(function() {
        chessR.server.testObject(MyInfo);
    });
    

    On signalR hub I write:

    public class GameHub : Hub
    {
        public void testObject(Object MyInfo)
        {
            Clients.Caller.testObject(MyInfo);
        }
    }
    

    Now the problem solved.