zoukankan      html  css  js  c++  java
  • react中使用signalr总结

    安装signalr

    npm install @microsoft/signalr
    

      signalr.js 引入@microsoft/signalr

    import {
    	JsonHubProtocol,
    	HubConnectionState,
    	HubConnectionBuilder,
    	LogLevel
    } from '@microsoft/signalr';
    

      连接signalr

         componentDidMount() {
    		
    		this.FnsignalR()
    	}
    	
    	FnsignalR = async () =>{
    		
    		let token = "你的token"
    		// console.log(token,"----token signalr---")
              //调用热数据传入api token this.setupSignalRConnection("/api/hotdatahub",token) } startSignalRConnection = async connection => { try { await connection.start(); console.assert(connection.state === HubConnectionState.Connected); console.log('SignalR connection established'); } catch (err) { console.assert(connection.state === HubConnectionState.Disconnected); console.error('SignalR Connection Error: ', err); setTimeout(() => this.startSignalRConnection(connection), 5000); } }; //SignalRC setupSignalRConnection = (connectionHub, getAccessToken) => { const options = { logMessageContent: isDev, logger: isDev ? LogLevel.Warning : LogLevel.Error, accessTokenFactory: () => getAccessToken }; // create the connection instance // withAutomaticReconnect will automatically try to reconnect // and generate a new socket connection if needed const connection = new HubConnectionBuilder() .withUrl(connectionHub, options) .withAutomaticReconnect() .withHubProtocol(new JsonHubProtocol()) .configureLogging(LogLevel.Information) .build(); // Note: to keep the connection open the serverTimeout should be // larger than the KeepAlive value that is set on the server // keepAliveIntervalInMilliseconds default is 15000 and we are using default // serverTimeoutInMilliseconds default is 30000 and we are using 60000 set below connection.serverTimeoutInMilliseconds = 60000; // re-establish the connection if connection dropped connection.onclose(error => { console.assert(connection.state === HubConnectionState.Disconnected); console.log('Connection closed due to error. Try refreshing this page to restart the connection', error); }); connection.onreconnecting(error => { console.assert(connection.state === HubConnectionState.Reconnecting); console.log('Connection lost due to error. Reconnecting.', error); }); connection.onreconnected(connectionId => { console.assert(connection.state === HubConnectionState.Connected); console.log('Connection reestablished. Connected with connectionId', connectionId); }); this.startSignalRConnection(connection); connection.on('hotdata', res => { console.log("SignalR get hot res:", JSON.parse(res)) let resdata = JSON.parse(res) }); return connection; };

      

  • 相关阅读:
    linux 运维
    mariadb replication
    phpmyadmin
    Objective-C设计模式——单例Singleton(对象创建)
    收藏iOS学习资料
    axios拦截器
    vue单页面优化
    html设置http缓存代码
    js数组去重,排序的几种方法
    前端移动端问题
  • 原文地址:https://www.cnblogs.com/baiyq/p/13497903.html
Copyright © 2011-2022 走看看