How to disconnect SignalR form client side to achieve timeout funcitonality - c#

I have client-side code that sends requests to server for some data. Sometime server don't respond and it take too long to establish connection. I want to set some timeout functionality on client-side so after that timeout, client will stop to try connecting server. In simple web request we can use timeout functionality. For example I am using the following code somewhere else and it is working fine for non-signalr request.
But when I send request through signalr, I can not set timeout to end this request and show user a message that data could not be fetched from server.
On this site someone suggested "Send a specific string to the client to force the disconnect" but that is not my scenario. I want to handle it on client side.
var refit = RestService.For<SomeApi>(new HttpClient
{
BaseAddress = new Uri(BASE_URL),
Timeout = TimeSpan.FromSeconds(30)
});

Related

SignalR: How to disconnect clients from server?

We currently have a Web Application, a SignalR Server and a RabbitMQ Server. The Web application receives events from SignalR based on the events received via RabbitMQ. Our Web Application has a fallback which, in case the connection to SignalR closes and can't be established, has a polling mechanism to try to keep the data updated.
The problem: If, instead of the SignalR server, the RabbitMQ is having issues, then, from the perspective of teh WebApplication it is still connected to SignalR server, which prevents it from polling data.
The possible solution: On the event of the RabbitMQ Server has issues connecting to SignalR, we would like to the SignalR server to actively refuse connections on a specified Hub and terminate all the connections it has.
Based on that i tried the following approach (inside the specified Hub), but no success:
public async override Task OnConnectedAsync()
{
var feature = Context.Features.Get<IConnectionHeartbeatFeature>();
feature.OnHeartbeat(state =>
{
try
{
if (rabbitMQWorker.IsConnected == false)
Context.Abort();
}
catch
{
}
}, Context.ConnectionId);
await base.OnConnectedAsync();
}
Even if it worked, I would still need to refuse any connections. Is this something feasable or am I heading towards the wrong direction?

Connect TcpClient through Fiddler proxy

How can I use a Fiddler proxy with a TcpClient? The answer on this similar question did not work for me: How to use Proxy with TcpClient.ConnectAsync()?
var client = new Pop3Client();
var tcpClient = new TcpClient(hostname, port);
var sslStream = new SslStream(tcpClient.GetStream());
sslStream.AuthenticateAsClient(hostname);
client.Connect(sslStream);
After some discussion it turned out that the code to create a connection through a proxy which was referenced in the question actually worked, but
SSL decryption need to be off in Fiddler.
Otherwise Fiddler will not pass the original TLS handshake through but will create one between Fiddler and Server and another one between Client and Fiddler, where the last one has a certificate created by Fiddler. The client will usually not trust this certificate by default and thus fail the TLS handshake.
Moreover, Fiddler expects the traffic inside the TLS connection to be HTTP, i.e. the client sends a HTTP request and the server sends a HTTP response back. POP3 works differently by having both a different message syntax and by having the server start with sending and not the client.
It really has to be client.Connect(sslStream) as shown in the question and not something like client.Connect(tcpStream) as the OP had in its actual code. In the last case the client will just try to read the encrypted data from the connection and thus fail.

C# client/server web proxy

I want to implement a client/server web proxy like this:
I set the proxy in web browser as 127.0.0.1:8080. I want catch every tcp request and send it to a server and get the response of that request and send it back to client. for example my client request is https://www.google.com and client send it to server and server get it's page and send it back to client and client can see google.com in the browser. how can I implement this? Is there any open-source project like this?
var tcpListener = new TcpListener(IPAddress.Any, 8080);
tcpListener.Start();
Console.WriteLine("Listening...");
var result = (IAsyncResult)tcpListener.BeginAcceptTcpClient(RespCallback, tcpListener);
//...
//???

How to send updates from server to clients?

I am building a c#/wpf project.
It's architecture is this:
A console application which will be on a virtual machine (or my home computer) that will be the server side.
A wpf application that will be the client app.
Now my problem is this - I want the server to be able to send changes to the clients. If for example I have a change for client ABC, I want the server to know how to call a service on the clients computer.
The problem is, that I don't know how the server will call the clients.
A small example in case I didn't explain it well:
The server is on computer 1, and there are two clients, on computers 2 and 3.
Client 2 has a Toyota car and client 3 has a BMW car.
The server on computer 1 wants to tell client 2 that it has a new car, an Avenger.
How do I keep track and call services on the clients?
I thought of saving their ip address (from calling ipconfig from the cmd) in the DB - but isn't that based on the WI-FI/network they are connected to?
Thanks for any help!
You could try implementing SignalR. It is a great library that uses web sockets to push data to clients.
Edit:
SignalR can help you solve your problem by allowing you to set up Hubs on your console app (server) that WPF application (clients) can connect to. When the clients start up you will register them with a specified Hub. When something changes on the server, you can push from the server Hub to the client. The client will receive the information from the server and allow you to handle it as you see fit.
Rough mockup of some code:
namepsace Server{}
public class YourHub : Hub {
public void SomeHubMethod(string userName) {
//clientMethodToCall is a method in the WPF application that
//will be called. Client needs to be registered to hub first.
Clients.User(userName).clientMethodToCall("This is a test.");
//One issue you may face is mapping client connections.
//There are a couple different ways/methodologies to do this.
//Just figure what will work best for you.
}
}
}
namespace Client{
public class HubService{
public IHubProxy CreateHubProxy(){
var hubConnection = new HubConnection("http://serverAddress:serverPort/");
IHubProxy yourHubProxy = hubConnection.CreateHubProxy("YourHub");
return yourHubProxy;
}
}
}
Then in your WPF window:
var hubService = new HubService();
var yourHubProxy = hubService.CreateHubProxy();
yourHubProxy.Start().Wait();
yourHubProxy.On("clientMethodToCall", () => DoSometingWithServerData());
You need to create some kind of subscription model for the clients to the server to handle a Publish-Subscribe channel (see http://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html). The basic architecture is this:
Client sends a request to the messaging channel to register itself as a subscriber to a certain kind of message/event/etc.
Server sends messages to the channel to be delivered to subscribers to that message.
There are many ways to handle this. You could use some of the Azure services (like Event hub, or Topic) if you don't want to reinvent the wheel here. You could also have your server application track all of these things (updates to IP addresses, updates to subscription interest, making sure that messages don't get sent more than once; taking care of message durability [making sure messages get delivered even if the client is offline when the message gets created]).
In general, whatever solution you choose is plagued with a common problem - clients hide behind firewalls and have dynamic IP addresses. This makes it difficult (I've heard of technologies claiming to overcome this but haven't seen any in action) for a server to push to a client.
In reality, the client talks and the server listens and response. However, you can use this approach to simulate a push by;
1. polling (the client periodically asks for information)
2. long polling (the client asks for information and the server holds onto the request until information arrives or a timeout occurs)
3. sockets (the client requests server connection that is used for bi-directional communication for a period of time).
Knowing those terms, your next choice is to write your own or use a third-party service (azure, amazon, other) to deliver messages for you. I personally like long polling because it is easy to implement. In my application, I have the following setup.
A web API server on Azure with and endpoint that listens for message requests
A simple loop inside the server code that checks the database for new messages every 100ms.
A client that calls the API, handling the response.
As mentioned, there are many ways to do this. In your particular case, one way would be as follows.
Client A calls server API to listen for message
Server holds onto call, waiting for new message entry in database
Client B calls server API to post new message
Server saves message to database
Server instance from step 2 sees new message
Server returns message to Client A.
Also, the message doesn't have to be stored in a database - it just depends on your needs.
Sounds like you want to track users à la https://www.simple-talk.com/dotnet/asp.net/tracking-online-users-with-signalr/ , but in a desktop app in the sense of http://www.codeproject.com/Articles/804770/Implementing-SignalR-in-Desktop-Applications or damienbod.wordpress.com/2013/11/20/signalr-a-complete-wpf-client-using-mvvm/ .

Multiple website server side Clients.All.receiveNotification challenge with SignalR

So I have two websites that I am using SignalR and I have the following in both my Global.asax files:
HubConfiguration hubConfig = new HubConfiguration();
hubConfig.EnableCrossDomain = true;
RouteTable.Routes.MapHubs(hubConfig);
I have a server side event side and I get the hub context to send a message to all listening clients:
var signalrContext = GlobalHost.ConnectionManager.GetHubContext<Notifications.OfferHub>();
signalrContext.Clients.All.receiveNotification("hello world");
The same event happens server side on both websites and I would like to broadcast this cross-domain to all listening clients. I am thinking this is not possible server side because I will not be able to get the HubContext for both websites change the hub.url server side.
Unless anyone has any other suggestions?
Well, it took me a minute to realize what do here. Thanks to David Fowler for his help and SignalR awesomeness! I ended up adding a ServiceReference in each website to a web service in the other website and calling a "Broadcast" WebMethod. The web service webmethod just gets the current SignalR context and broadcasts my message to all clients listening on the respective website.

Categories

Resources