var connection = new signalR.HubConnectionBuilder().withUrl(hubUrl).build(); var connectionId; function connect() { console.log('check connection state :' + connection.state); if (connection.state === signalR.HubConnectionState.Disconnected) { connection.start().then(function () { console.log('connect successful'); }).catch(function () { console.log('connect failed'); setTimeout(connect,5000); }); } } connection.onclose(function () { console.log('connect closed'); connect(); }); connection.on('Connected', function (id) { connectionId = id; console.log('signalR 连接Id:' + connectionId); }); connection.on("ServerToClient", function (method, message, to, from) { console.log(method + ':' + message); onMessage(method, message, to, from); });