RPC/RMI
How to set properties on the server from the client
Since we have state on all controllers in the connection and can take advantage of that we can store information server side and not send trivial things like a user name each time we want to communicate.
Server
A simple model for a chat
public class ChatModel
{
public string UserName {get;set;}
public string Text {get;set;}
}
A controller where we use state to only send in text since the username is known.
//using XSockets.Core.XSocket;
//using XSockets.Core.XSocket.Helpers;
public class Chat : XSocketController
{
public string UserName {get;set;}
public async Task ChatMessage(ChatModel message)
{
message.UserName = this.UserName;
await this.InvokeToAll(message,"chatmessage");
}
}
Client
conn.controller('chat').setProperty('username','David');
How to call server methods from the client
Server
A simple model for a chat
public class ChatModel
{
public string UserName {get;set;}
public string Text {get;set;}
}
A controller where we use state to only send in text since the user name is know. See How to set properties on the server from the client
//using XSockets.Core.XSocket;
//using XSockets.Core.XSocket.Helpers;
public class Chat : XSocketController
{
public string UserName {get;set;}
public async Task ChatMessage(ChatModel message)
{
message.UserName = this.UserName;
await this.InvokeToAll(message,"chatmessage");
}
}
Client
Since we already have set the property of UserName
on the server we only need to send the Text
property
conn.controller('chat').invoke('chatmessage',{Text:'Calling chatmessage on server and passing a part of the complex object'});
How to define methods on the client that the server can call
To define a method that the server can call from a Controller
just add a method to the controller in JavaScript. The parameters can be complex objects.
Method name has to be lowercase in the JavaScript API. For example:
this.Invoke('Hello from server','ChatMessage');
on the server will execute chatmessage
on the client.
Client
var conn = new XSockets.WebSocket('ws://localhost:4502',['chat']);
conn.controller('chat').chatmessage = function(data){
console.log(data.UserName + " - " + data.Text);
};
Server
A simple model for a chat
public class ChatModel
{
public string UserName {get;set;}
public string Text {get;set;}
}
A controller where we use state to only send in text since the user name is know. See How to set properties on the server from the client
//using XSockets.Core.XSocket;
//using XSockets.Core.XSocket.Helpers;
public class Chat : XSocketController
{
public string UserName {get;set;}
public async Task ChatMessage(ChatModel message)
{
message.UserName = this.UserName;
await this.InvokeToAll(message,"chatmessage");
}
}
How to call a server side method and wait for the result
Client
conn.controller('stockticker').invoke('getstocks').then(function(data){
console.log(data);
});
Server
public IEnumerable<Stock> GetStocks()
{
return _stockService.GetAll();
}