signalr
  1. signalr-javascript-clients

JavaScript Clients - SignalR Clients

Syntax

In order to create a SignalR client, we need to include the jquery.signalR.min.js and signalr/hubs scripts in our HTML file.

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<!-- SignalR -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.signalr/2.4.1/jquery.signalR.min.js"></script>
<script src="/signalr/hubs"></script>

After including these scripts, we can create a SignalR client by calling the $.hubConnection() function.

var hub = $.hubConnection();

// create a proxy
var proxy = hub.createHubProxy('hubName');

// subscribe to events
proxy.on('eventName', function(data) {

});

// start the connection
hub.start().done(function() {

});

Example

Here's an example of how to create a SignalR client and listen for events.

// create a connection
var hub = $.hubConnection();

// create a proxy
var proxy = hub.createHubProxy('chat');

// subscribe to events
proxy.on('send', function(name, message) {
  console.log(name + ': ' + message);
});

// start the connection
hub.start().done(function() {
  console.log('Connected to server.');

  // send a message
  proxy.invoke('send', 'John', 'Hello, world!');
});

Output

The output of the example above would be:

Connected to server.
John: Hello, world!

Explanation

The example above creates a SignalR client and connects to the server. It then creates a proxy for the chat hub and subscribes to the send event. When the event is triggered, it logs the name and message to the console. Finally, it sends a message to the server using the invoke method.

Use

SignalR clients are used to connect to SignalR servers and listen for events. They can also send messages to the server using the invoke method.

Important Points

  • SignalR clients require the jquery.signalR.min.js and signalr/hubs scripts
  • SignalR clients create a connection using $.hubConnection()
  • SignalR clients create a proxy using hub.createHubProxy()
  • SignalR clients subscribe to events using proxy.on()
  • SignalR clients start the connection using hub.start()
  • SignalR clients can send messages to the server using proxy.invoke()

Summary

JavaScript clients, more specifically, SignalR clients are a powerful tool to enable real-time communication between clients and servers. We can create a SignalR client by calling the $.hubConnection() function, and create a proxy by calling the hub.createHubProxy() function. We can then subscribe to events using the proxy.on() function and start the connection using the hub.start() function. Finally, we can send messages to the server using the proxy.invoke() method.

Published on: