Home  >  Article  >  Web Front-end  >  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:422582browse

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:


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

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('newChatMessage', {name:'a',message:'b'});

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('addMessageToList', function(userName, message) {
  console.log(userName + ' ' + 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({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      'root.jQuery': 'jquery'
    })
  ]

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 'element-ui';
const HUBNAME = 'DefaultHub';

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

/*服务器调用客户端方法*/
// 打印新订单
const printNewOrder = {
  name:'printNewOrder',
  method:function(data){
    console.log(data)
  }
}
const get = {
  name:'Get',
  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('Now connected, connection ID=' + connection.id)
  }).fail(()=>{
    Message('连接失败' + error);
    console.log('Could not connect');
  })
  hub.error(function (error) {
    Message('SignalR error: ' + error);
    console.log('SignalR error: ' + error)
  })
  hub.connectionSlow(function () {
    console.log('We are currently experiencing difficulties with the connection.')
  });
  hub.disconnected(function () {
    console.log('disconnected')
  });
  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