Struggling using SignalR in WP8 - c#

I have a Windows Phone 8 client.
I am using SignalR to communicate with my server.
I need my UI to update with messages from my server.
I know the server part is correct as I have set break points and have used a HTML5 client.
The issue is with WP8
I have never used WP8 before so I am not sure if I am doing it correctly.
I have this:
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
//not important for now LogIn();
}
});
connection.Received += data =>
{
UpdateConnectionState(data);
};
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
};
connection.Reconnected += () =>
{
UpdateConnectionState("The connection was re-established");
};
}
My UI initially states a connection has been made.
It is now receiving messages from the Server that I am stuck at. I have also tried this:
private async void UpdateTime(string data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
txtInfo.Text = data;
});
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
proxy.On<string>("internetUpTime", UpdateTime);
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
}
});
//connection.Received += data =>
//{
// UpdateConnectionState(data);
//};
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
};
connection.Reconnected += () =>
{
UpdateConnectionState("The connection was re-established");
};
}
Which way is the correct way and what is wrong with my code?
thanks

To handle calls from the server, use the following syntax:
proxy.On<PckType>("broadcastMessage", msg => {});
Where PckType is the type that is the equivalent to the type server sent with the following code:
Clients.Caller.broadcastMessage(pck);
SignalR acts as a RPC service which means methods called from the client must exist on the server and vice versa. Of course, this is only true for the Hub approach.

Related

Server handling client disconnects

Below this post, is my ChatApp's client disconnect handler, where it removed the disconnected client from the ListView, it perfectly but the CPU usage suddenly goes up to 50% when the client disconnects. How can I fix it?
Task.Factory.StartNew(() =>
{
while (true)
{
try
{
if (!client.Client.Connected)
{
session.Stop();
session.tcpclient = null;
Clients.Remove(session);
listView1.Invoke((MethodInvoker)(() =>
{
ListViewItem data = new ListViewItem(session.listItems);
listView1.Items.RemoveAt((session.index));
listView1.Refresh();
}));
}
Thread.Sleep(500);
}
catch (Exception)
{
}
}
});
I tried putting it in a Thread but didn't work.

Signal R reconnect seems to create a new thread

We have a siglnalR hub hosted in IIS, and a WPF .net core application that connects. Everything is working perfectly on first run. However, when IIS recycles the application pool, the WPF client re-reconnects successfully, but, (so it seems) on another thread, as when the user attempts to perform an action (open a new WPF window) - the following error is thrown when creating a new instance of the window to open :-
"The calling thread must be STA, because many UI components require this"
This is how we connect to the hub :-
private async void Connect()
{
try
{
_signalRConnection.On<Notification>(NotificationMessageStr, (message) =>
{
if (message != null && _signalRConnection != null)
{
OnProcessMessage(message);
}
}
);
_signalRConnection.Reconnecting += error =>
{
OnReconnecting("Connection lost - Attempting to reconnect.");
return Task.CompletedTask;
};
_signalRConnection.Reconnected += connectionId =>
{
OnReconnected("Reconnected");
return Task.CompletedTask;
};
_signalRConnection.Closed += error =>
{
OnLostConnection("Failed to connect");
// Notify users the connection has been closed or manually try to restart the connection.
return Task.CompletedTask;
};
try
{
//Connect to the server
await _signalRConnection.StartAsync();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
When a message is received from the hub, we call :-
private void SubscriveToNewNotification()
{
vm.NewNotification += (sender, e) => {
ShowNotificationAlert(e.NotificationMessage); };
}
private void ShowNotificationAlert(Notification notification) {
NotificationAlert notificationAlert = new NotificationAlert();
notificationAlert.notification = notification;
notificationAlert.Show();
}
And it is this:-
NotificationAlert notificationAlert = new NotificationAlert();
That is failing.
This is how the connection is built up :-
private void InitializeViewModel()
{
try
{
string serviceAddress = "xxxx/notificationHub";
connectHub = NotificationHubManager.CreateNotificationHub(serviceAddress, userInfo);
}
catch (System.Exception ex)
{
System.Windows.MessageBox.Show(ex.Message + "--");
}
connectHub.ProcessMessage += (sender, e) =>
{
// THIS IS WHERE IT FALLS OVER
NotificationAlert n = new NotificationAlert();
OnNotificationReceived(e.NotificationMessage);
};
-- This is the notification hub
public static NotificationHubConnect CreateNotificationHub(string address, ISwiftUser userInfo = null)
{
HubConnection hubConnection = new HubConnectionBuilder()
.WithUrl(address)
.WithAutomaticReconnect()
.Build();
try
{
var result = new NotificationHubConnect(hubConnection, userInfo);
return result;
}
catch (Exception ex)
{
throw ex;
}
}
Is there a way to have the reconnect run on the same thread?

C# - Signalr client connection is causing performance issue Windows Service

Signalr client code is causing performance issue is Windows Service. Windows service is acting as signalr client.
What we are trying to do:
Windows service is having one timer, which executes the method(ConnectToSignalRServer). If somehow the connection gets closed, there is one event (Connection.Closed += Connection_Closed), which will again try to establish the connection by calling the method(ConnectToSignalRServer). A while loop is being used in the event (Connection.Closed += Connection_Closed) to try reconnecting.
Please find the sample code below and let me know if any issues with the code.
private static HubConnection Connection = null;
//When the service starts, this method would be called.
public static bool ConnectToSignalRServer()
{
try
{
string Url = "http://www.samplesignalrserver.com";
Connection = new HubConnection(Url);
var myHub = Connection.CreateHubProxy("SignalHub");
Connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
}
else
{
Connection.Closed += Connection_Closed;
}
}).Wait();
//Method(RequestData) would be called upon receiveng message from server
myHub.On<string>("GetMessgeFromServer", type =>
{
Task.Run(() => RequestData(type));
});
//Method(GetHostName) would be called in server
myHub.Invoke<string>("GetHostName", BLConstants.strHostName);
return true;
}
catch (Exception ex)
{
//capturing Stacktrace and Message from ex object
}
return false;
}
//Establish the connection, if the the connection would be closed
private static void Connection_Closed()
{
try
{
while (true)
{
Thread.Sleep(10000);
bool connected = ConnectToSignalRServer();
if (connected)
{
break;
}
}
}
catch (Exception ex)
{
//capturing Stacktrace and Message from ex object
}
}

Sending data via sockets from c# to a node socket.io server

I am currently trying to feed my socket.io server with data from my C# client. But I am not sure how to receive the message on the server.
My server code:
const io = require('socket.io')(9000);
io.on('connection', (socket) => {
console.log('Connected');
}
First of all I don't know which event I have to listen to, but nevertheless I am unable to send data to my server using the following client (which uses Websocket-sharp) code:
private void init()
{
// start socket connection
using (var ws = new WebSocket("ws://localhost:9000/socket.io/?EIO=2&transport=websocket"))
{
ws.OnMessage += (sender, e) =>
API.consoleOutput("Message: " + e.Data);
ws.OnError += (sender, e) =>
API.consoleOutput("Error: " + e.Message);
ws.Connect();
ws.Send("server");
}
}
The connection works, but how do I receive the message of the server? The sending does not fire an error, therefore I think it does work.
I've gotten this working for a UWP app that connects to a node.js server. Basically what I do is connect to a URL that looks like ws://localhost:4200/socket.io/?EIO=3&transport=websocket
the port number being something we chose.
once that is set I connect to the node.js socket io library via the following lines of code.
private async Task ConnectWebsocket() {
websocket = new MessageWebSocket();
Uri server = new Uri(WebSocketURI); //like ws://localhost:4300/socket.io/?EIO=3&transport=websocket
websocket.Control.MessageType = SocketMessageType.Utf8;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Closed += Websocket_Closed;
try {
await websocket.ConnectAsync(server);
isConnected = true;
writer = new DataWriter(websocket.OutputStream);
}
catch ( Exception ex ) // For debugging
{
// Error happened during connect operation.
websocket.Dispose();
websocket = null;
Debug.Log("[SocketIOComponent] " + ex.Message);
if ( ex is COMException ) {
Debug.Log("Send Event to User To tell them we are unable to connect to Pi");
}
return;
}
}
`
at this point your socket io on "connection" should fire on your server
then you can emit events to it like normal. except the C# socket code does not discriminate various channels so you must do so on your own. below is how we do it (aka SocketData and SocketIOEvent are classes we have defined)
private void Websocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) {
try {
using ( DataReader reader = args.GetDataReader() ) {
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
try {
string read = reader.ReadString(reader.UnconsumedBufferLength);
//read = Regex.Unescape(read);
SocketData socc = SocketData.ParseFromString(read);
if (socc != null ) {
Debug.Log(socc.ToString());
SocketIOEvent e = new SocketIOEvent(socc.channel, new JSONObject( socc.jsonPayload));
lock ( eventQueueLock ) { eventQueue.Enqueue(e); }
}
}
catch ( Exception ex ) {
Debug.Log(ex.Message);
}
}
} catch (Exception ex ) {
Debug.Log(ex.Message);
}
}
in our specific application we did not need to send messages to our server, so for that I do not have a good answer.

Receive Whatsapp Message using WhastApp API 1.2.2 (Nuget) in C#

I use visual studio 2012 and I use whatsap api in my project (downloaded from Nuget), I already develop some code to send whatsapp message to another number,
but I want to know how can i receive message from other numbers?
which event should i use? and how to keep my application always listen to incoming messages.
my code to send is:
static string from = "9********";
static WhatsApp wa = new WhatsApp(from, "*******w=", "Az", false, true);
private void button1_Click(object sender, EventArgs e)
{
try
{
string to = txt_To.Text.Trim();
string msg = txt_Message.Text.Trim();
wa.OnConnectSuccess += () =>
{
MessageBox.Show("Connected Successfully");
wa.OnLoginSuccess += (phoneNumber, data) =>
{
wa.SendMessage(to, msg);
MessageBox.Show("Message Sent ...");
};
wa.OnLoginFailed += (data) =>
{
MessageBox.Show("Login Faild ...");
};
wa.Login();
};
wa.OnConnectFailed += (ex) =>
{
MessageBox.Show("Connected Faild ...");
};
wa.Connect();
wa.Login();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
My application is wondows application
any one can help me?

Categories

Resources