1. 程式人生 > 實用技巧 >react中使用signalr總結

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; };