Home >Web Front-end >JS Tutorial >Vue combines SignalR front-end and front-end real-time message synchronization implementation method

Vue combines SignalR front-end and front-end real-time message synchronization implementation method

小云云
小云云Original
2018-02-05 16:15:422764browse

This article mainly introduces Vue combined with SignalR to achieve front-end and back-end real-time message synchronization. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

In recent business, it is necessary to realize the real-time communication function between the server and the client, so I made a summary and arrangement of Signalr.

SignalR, as a library of ASP.NET, can simply and conveniently provide real-time server-side and client-side two-way communication functions for applications.

SignalR has two APIs on the client side: Connections and Hubs.

In special cases, such as when the format of the message sent is specific and unchanged, use the Connections API.

Hubs are used in most cases because it is a more advanced implementation of the Connections API, allowing the client and server to directly call methods on each other. A specific scenario of practical application, for example, when the server obtains a new order, it calls the client's printing method. After the client completes printing, it calls the server's order status update method.

The following introduces the API of Hubs on the front end

generated proxy

When using generated proxy, it is easier to call services at the syntax level Side method, just like calling it directly on the server side.

The following is the server code, which means adding a chat message to the list


public class DemoChatHub : Hub
{
  public void NewChatMessage(string name, string message)
  {
    Clients.All.addMessageToList(name, message);
  }
}

When called by the client:


var demoChatHubProxy = $.connection.DemoChatHub;
demoChatHubProxy.client.addMessageToList = function (name, message) {
  console.log(name + ' ' + message);
};
$.connection.hub.start().done(function () {
 
  $('#newChatMessage').click(function () {
     demoChatHubProxy.server.newChatMessage($('#displayname').val(), $('#message').val());
   });
});

When generated proxy is not used, when the client calls it, it is


var connection = $.hubConnection();
var demoChatHubProxy = connection.createHubProxy('demoChatHub');
demoChatHubProxy.on('addMessageToList', function(name, message) {
  console.log(name + ' ' + message);
});
connection.start().done(function() {
  $('#newChatMessage').click(function () {
    demoChatHubProxy.invoke('newChatMessage', $('#displayname').val(), $('#message').val());
    });
});

. However, in the Vue project, if the front and back ends are separated, no It will be quoted like this:


<script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>

And if you want to use multiple event handlers in the client method, you cannot use generated proxy.

Therefore, the following examples do not use generated proxy.

1. How to establish a connection


##

var connection = $.hubConnection(&#39;localhost:23123&#39;);//如果前后端为同一个端口,可不填参数。如果前后端分离,这里参数为服务器端的URL
var demoChatHubProxy = connection.createHubProxy(&#39;demoChatHub&#39;);
demoChatHubProxy.on(&#39;addMessageToList&#39;, function(userName, message) {
  console.log(userName + &#39; &#39; + message);
}); 
connection.start()
  .done(function(){ console.log(&#39;Now connected, connection ID=&#39; + connection.id); })
  .fail(function(){ console.log(&#39;Could not connect&#39;); });

It should be noted that before starting the connection (before calling the start method) , it is best to register at least one event processing method.

If it is not registered, the OnConnected method of Hubs will not be called, and then the client's method cannot be called by the server (this is easy to bury, so the method must be registered in advance) .

2. How the client calls the server-side method
Use invoke. Note that the first letter of the method name when calling the server does not need to be capitalized. If the method name is restricted, it must be capitalized. Backend configuration is required.


demoChatHubProxy.invoke(&#39;newChatMessage&#39;, {name:&#39;a&#39;,message:&#39;b&#39;});

3. The server calls the client method

First the client must register the method before the server can call it , use the on method to register.


demoChatHubProxy.on(&#39;addMessageToList&#39;, function(userName, message) {
  console.log(userName + &#39; &#39; + message);
});

4 Use SignalR in the Vue project

First install the SignalR package. What you need to pay attention to is the SignalR dependency. jQuery.

npm i signalr,jquery

For convenience, register global jQuery in webpack.base.conf.js


plugins: [new webpack.ProvidePlugin({
      $: &#39;jquery&#39;,
      jQuery: &#39;jquery&#39;,
      &#39;window.jQuery&#39;: &#39;jquery&#39;,
      &#39;root.jQuery&#39;: &#39;jquery&#39;
    })
  ]

Then introduce SignalR in main.js

import 'signalr'

You can use it in the Vue project at this time SignalR, the related configuration of the backend is temporarily skipped.

Create a new signalr.js


import { Message } from &#39;element-ui&#39;;
const HUBNAME = &#39;DefaultHub&#39;;

/*客户端调用服务器端方法*/
//更新订单打印次数
const updateOrderPrint = {
  name:&#39;updateOrderPrint&#39;,
  method:function(data){
    console.log(data)
  }
}

/*服务器调用客户端方法*/
// 打印新订单
const printNewOrder = {
  name:&#39;printNewOrder&#39;,
  method:function(data){
    console.log(data)
  }
}
const get = {
  name:&#39;Get&#39;,
  method:function(data){
    console.log(data)
  }
}

//服务器端的方法
const serverMethodSets = [updateOrderPrint];
//客户端的方法
const clientMethodSets = [printNewOrder,get]; //将需要注册的方法放进集合

// 建立连接
export function startConnection() {
  let hub = $.hubConnection(process.env.HUB_API)
  let proxy = createHubProxy(hub) //需要先注册方法再连接
  hub.start().done((connection) =>{
    console.log(&#39;Now connected, connection ID=&#39; + connection.id)
  }).fail(()=>{
    Message(&#39;连接失败&#39; + error);
    console.log(&#39;Could not connect&#39;);
  })
  hub.error(function (error) {
    Message(&#39;SignalR error: &#39; + error);
    console.log(&#39;SignalR error: &#39; + error)
  })
  hub.connectionSlow(function () {
    console.log(&#39;We are currently experiencing difficulties with the connection.&#39;)
  });
  hub.disconnected(function () {
    console.log(&#39;disconnected&#39;)
  });
  return proxy
}
// 手动创建proxy
export function createHubProxy(hub){
  let proxy = hub.createHubProxy(HUBNAME)
  // 注册客户端方法
  clientMethodSets.map((item)=>{
    proxy.on(item.name,item.method)
  })
  return proxy
}

In this way, the connection can be established by calling the startConnection method after introducing signalr.js into the component.

Related recommendations:


Python implements WeChat group message synchronization robot based on itchat

The above is the detailed content of Vue combines SignalR front-end and front-end real-time message synchronization implementation method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn