Giter Club home page Giter Club logo

react-native-signalr's Introduction

react-native-signalr

Connect to your SignalR-server with a active websocket-connection from react-native. Supports all error-handling and reconnection, including longpolling if needed.

Today the module shims the jQuery-dependency that signalr has. There is however an ongoing task upstream to remove this dependency.

Does NOT pull in the entire jQuery-library. Only shimes the few methods SignalR needs. Tested on iOS and Android. No known issues.

Install:

npm i react-native-signalr --save

There is an example server setup at https://react-native-signalr.olofdahlbom.se (Also a http version but you must disable App security transport on iOS for that, read in issues) (no webite, only responds to signalr) If it's up and running, you can use it to debug against. You can find the source for that server under examples/server. The code below uses that server to setup a connection and communicate over websockets using signalr.

Awesome-project:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import signalr from 'react-native-signalr';

class AwesomeProject extends Component {

  componentDidMount() {
    //This is the server under /example/server published on azure.
    const connection = signalr.hubConnection('https://react-native-signalr.olofdahlbom.se');
    connection.logging = true;

    const proxy = connection.createHubProxy('chatHub');
    //receives broadcast messages from a hub function, called "helloApp"
    proxy.on('helloApp', (argOne, argTwo, argThree, argFour) => {
      console.log('message-from-server', argOne, argTwo, argThree, argFour);
      //Here I could response by calling something else on the server...
    });

    // atempt connection, and handle errors
    connection.start().done(() => {
      console.log('Now connected, connection ID=' + connection.id);

      proxy.invoke('helloServer', 'Hello Server, how are you?')
        .done((directResponse) => {
          console.log('direct-response-from-server', directResponse);
        }).fail(() => {
          console.warn('Something went wrong when calling server, it might not be up and running?')
        });

    }).fail(() => {
      console.log('Failed');
    });

    //connection-handling
    connection.connectionSlow(() => {
      console.log('We are currently experiencing difficulties with the connection.')
    });

    connection.error((error) => {
      const errorMessage = error.message;
      let detailedError = '';
      if (error.source && error.source._response) {
        detailedError = error.source._response;
      }
      if (detailedError === 'An SSL error has occurred and a secure connection to the server cannot be made.') {
        console.log('When using react-native-signalr on ios with http remember to enable http in App Transport Security https://github.com/olofd/react-native-signalr/issues/14')
      }
      console.debug('SignalR error: ' + errorMessage, detailedError)
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

react-native-signalr's People

Contributors

mlabrum avatar olofd avatar perkola avatar xahon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-signalr's Issues

Autoreconnect feature

Hi,

possible to have the equivalent of js signalr client "@microsoft/signalr" autoreconnect feature ?
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.withAutomaticReconnect()
.build();
I didn't find any disconnect catcher, so after a while, when connection is lost, i can't do anything to reconnect the user.

how can change state from on(event)

hello
my code is
proxy.on('changeNotificationslist', function (data) {
this.setState({notifications: this.state.notifications.push(data)})
});
but it give error that setState is not a function
is there any solution for state inside (event)

thanks

Cannot add authorization header

I'm trying to connect to my hub, however it requires an Authorization header to be present. I'm looking through the code and documentation, and I cannot find anyway to add said header to the XMLHttpRequest that gets sent.

Due to this I get 401s during the connection. Is there any way to add headers currently?

Failed - Error: Error during negotiation request.

Error

Failed - Error: Error during negotiation request.
    at Object.error (jquery.signalR.js:179)
    at onFailed (jquery.signalR.js:652)
    at Object.error (jquery.signalR.js:672)
    at EventTarget.request.onreadystatechange (ajax.js:23)
    at EventTarget.dispatchEvent (event-target-shim.js:818)
    at EventTarget.setReadyState (XMLHttpRequest.js:592)
    at EventTarget.__didCompleteResponse (XMLHttpRequest.js:395)
    at XMLHttpRequest.js:508
    at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
    at MessageQueue.__callFunction (MessageQueue.js:416)
jquery.signalR.js:82 [13:01:40 GMT+0530 (India Standard Time)] SignalR: Stopping connection.

My Code

componentDidMount() {
    //This is the server under /example/server published on azure.
    const connection = signalr.hubConnection('https://react-native-signalr.olofdahlbom.se');
    connection.logging = true;

    const proxy = connection.createHubProxy('chatHub');
    //receives broadcast messages from a hub function, called "helloApp"
    proxy.on('helloApp', (argOne, argTwo, argThree, argFour) => {
      console.log('message-from-server', argOne, argTwo, argThree, argFour);
      //Here I could response by calling something else on the server...
    });

    // atempt connection, and handle errors
    connection.start().done(() => {
      console.log('Now connected, connection ID=' + connection.id);

      proxy.invoke('helloServer', 'Hello Server, how are you?')
        .done((directResponse) => {
          console.log('direct-response-from-server', directResponse);
        }).fail(() => {
          console.warn('Something went wrong when calling server, it might not be up and running?')
        });

    }).fail(() => {
      console.log('Failed');
    });

    //connection-handling
    connection.connectionSlow(() => {
      console.log('We are currently experiencing difficulties with the connection.')
    });

    connection.error((error) => {
      const errorMessage = error.message;
      let detailedError = '';
      if (error.source && error.source._response) {
        detailedError = error.source._response;
      }
      if (detailedError === 'An SSL error has occurred and a secure connection to the server cannot be made.') {
        console.log('When using react-native-signalr on ios with http remember to enable http in App Transport Security https://github.com/olofd/react-native-signalr/issues/14')
      }
      console.debug('SignalR error: ' + errorMessage, detailedError)
    });
  }

Server side OnConnected() not triggered

Server side OnConnected() is not been called whenever the client establishes a connection.
public override Task OnConnected() { return base.OnConnected(); }
The same goes to OnDisconnected().

Even though the server method is not been called, there is still a connection between the client and server, and a connection id is generated.

Please advice.
I'm using the following libs:
react-native-signalr: 0.0.10
react-native: 0.39.0

Group cannot receive message

Hi,
Im using Azure as server.

And my environment is as follows:
Client 1: Web browser with Signalr JS installed
Client 2: React-native app

Server:
Asp.net C# Server with Signalr

When a client invoke a message , people in the group will receive messages.
My web browser(Client1) received message successfully but my react-native app (Client2) didn't.

`
componentDidMount() {

    const connection = signalr.hubConnection('http://signalrpj.azurewebsites.net');
    connection.logging = true;

    const proxy = connection.createHubProxy('chatHub');

    proxy.on('addMessage', (message1) => {
        console.log('message-from-server Group', message1);
        if (message1 == 'openMindwavePage') {
            proxy.invoke('send', this.props.login_account, 'haveOpened');
            this.props.MindWave();
            connection.stop();
        }
    });


    connection.start().done(() => {
        proxy.invoke('group', 'this.props.login_account');
        console.log('Now connected, connection ID=' + connection.id);
    }).fail(() => {
        console.log('Failed');
    });

}`

Please help ,Thanks
Joyce

Fails to send '&'

Hi,
I tried sending '&' from the client to the server as shown below:
let fake = {key:'Helloworld', user:{name:'&', statement:'test', avatar:'http://graph.facebook.com/1015477/picture?type=square&width=300&height=300'}}

and I got this error:
[JsonReaderException: Unterminated string. Expected delimiter: &quot;. Path &#39;A&#39;, line 1, position 89.] Newtonsoft.Json.JsonTextReader.ReadStringIntoBuffer(Char quote)

However, if I did not have a load balancer in front of my socket server, this problem does not occurs.

Is there any thing I need to set up at the client or server side in order to parse special character correctly?

I am using:
C# Signalr for Server (latest version)
AWS Load balancer
React-native Signalr for Client (latest version)

Does it support Net Core 2.1 or later?

What latest version does it support?
I am trying to connect in a native native (android) application with a server in Net Core 2.1 and it does not work. There is a chance that it does not support

Signal R not working with ANDROID STORE VERSION

I have created an app with Signal R 1.0.6. When I make an APK and test it locally, Singnal R is perfectly working.

But once I put it to the store, the Singal R functions are not working. To put to store, i am using the bundle function.

Is there any dependency/automatic changes when i Bundle it and put it to store. Could you please help me with this issue.

Question: Using Query String

Hi,

Just a simple query, how do I include query string using this library? The example in C# would be as follows:

var qs = "username=rendang";
var url = "http://192.168.93.139/SignalRHub/";
hubConnection = new HubConnection(url, qs);

Do we have the equivalent way of doing this? I tried using the traditional way using this library, but doesn't seem to work ie:

let qs = "username=rendang";
let url = "http://192.168.93.139/SignalRHub";
let fullUrl = url + "?" + qs;
const connection = signalr.hubConnection(fullUrl);

And this way as well:

let qs = "username=rendang";
let url = "http://192.168.93.139/SignalRHub";

    let fullUrl = url;
    const connection = signalr.hubConnection(fullUrl, qs);

Appreciate some advice.

Note: Sorry, I am very new to JS and ES6 language.

Set hubProxy to variable

Hello,

is it possible to set a HubProxy to a variable and access its methods?
For example:

conectarChat()  {
    const connection = signalr.hubConnection(url);
    connection.logging = true;
 
    const proxy = connection.createHubProxy('chatHub');

    this.proxy_signalr = proxy;
    
    // ... connection start and other stuff
}
componentDidMount() {
 this.conectarChat();
 
 this.proxy_signalr.on('msgRecebida', (id_enviou, id_recebeu, mensagem) => {
      //some function
 });
}

If the .on method is within conectarChat() function it works perfectly.

Thanks,
Bruno

Compatibility with Webpack 2.2.0

Hej!

First of, great work with this lib 👌 . I can wait until Microsoft releases their re-take on SignalR, so that we finally can get rid of the jQuery dependency altogether. Until then, I thought I'd try out this neat workaround.

The project I'm currently working on uses the latest version of Webpack (2.2.1). I get the following error when trying to import from the module

> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

It looks like the same problems reported over at webpack's repo. In short it looks like module.exports is readonly when using ES2015 modules.

Do you have any plans for making this package compatible with contemporary modules?

Keep up the good work!

How to connect to development server?

I'm following the example code and I've set up a Hub like so:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }

And my dev server can be reached from localhost:64726. However what do I replace in the following line?

var connection = signalr.hubConnection('http://<your-signalr-server-url>');

I have tried http://localhost:64726, http://10.0.2.2:64726 and more but all give the same result:

Error: Error during negotiation request.

Any ideas on how to connet my React Native App to SignalR?

Edit: trying to access http://10.0.2.2:64726 in the emulator browsers yields

Bad Request - Invalid Hostname

--------------------------------------------------------------------------------

HTTP Error 400. The request hostname is invalid.

Subtle bug in jquery-function

Hi!

I found a very subtle bug in jquery-function that impacts the functioning of this library with signalr client.
It's about this line of code:

const events = subject.events || {};

You are caching the events instance and using that reference to call the bind, unbind and triggerHandler functions. That is a problem because signalr caches this reference sometimes but other times it doesn't and calls to bind/unbind will make the cached copies have a stale events reference, so when it calls triggerHandler on a cached reference it will not find the bound callbacks because the bind was called on yet another jquery-function object.

I was having a problem caused by this. The scenario was when I received messages before the connection was moved to the "connected" state. When this happens, the signalr client buffers the messages and when it transitions to the connected state, it will drain this buffer and trigger onReceived event handlers.

But signalr was calling the triggerhandler on a cached jquery-function object, and the bind methods to onReceived on another, which causes the method I bound was not being called!

I fixed this by reading the events reference from subject in each function body call declared (unbind, bind and triggerHandler).

Do you understand what I am saying? If not, I can try to explain a little better :)

Can you provide an official fix, so that I can I have a permanent fix to this problem?
Many thanks!

Using transport webSockets gives error

Using the following code:

this.connection
        .start({
          transport: 'webSockets',
          data: { name: 'corehub' },
        })
        .done(() => {
          this.isConnected = true;
          console.log('is connected');
        })
        .fail((err) => {
          this.isConnected = false;
          console.log('error', err);
        });

I get the following error:

No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.

undefined is not an object: window.document.location.protocol

I am getting an error that I believe is coming from the example project leaking into the include. It is coming from jquery.signalR.js.

My import looks like this: import signalr from 'react-native-signalr'; and I installed the library using npm install react-native-signalr --save

Any thoughts?

img_0767

Unable to call signalR method

I am trying to connect signalR from react-native app. If I open the connection, before registering proxy, connection happens. When I register proxy before the connection is opened, it fails the negotiation. If I register the proxy.on after connection. function is not being called. Please advise.

`import React, {Component} from 'react';
import {Text, StyleSheet, View} from 'react-native';

import signalr from 'react-native-signalr';

export default class SignalTest extends Component {
constructor(props) {
super(props);
}
sendDriverUpdate = async => {
this.connection
.invoke('driverLocationUpdate', '2', '1.1221', '3.12312')
.catch(err => console.error(err));
};
componentDidMount() {
const connection = signalr.hubConnection('http://164.68.125.218', {
headers: {
token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImIiLCJuYmYiOjE1ODI4NzM2NDMsImV4cCI6MTU4NTQ2NTY0MywiaWF0IjoxNTgyODczNjQzLCJhdWQiOiIxNjQuNjguMTI1LjIxOCJ9.uRh1ExYW0y3RwYCOP6IetD_MEgkmyviwvW-_4iCQ_1k',
username: 'b',
driverid: 2,
},
});
connection.logging = true;

const proxy = connection.createHubProxy('AgentHub');

proxy.on(
  'driverLocationUpdate',
  (2, '1.1222', '3.23232'),
  msgfromserver => {
    console.log(msgfromserver, argOne, argTwo, argThree);
    //Here I could response by calling something else on the server...
  })

connection
  .start(() => {})
  .done(() => {
    
  })
  .fail(  (err, err1) => {
    console.log('Failed');
    console.log(err);
  });
/* connection.disconnected(function() {
  setTimeout(function() {
    connection.start().done(function() {
      console.log('reconnected');
    });
  }, 3000);
}); */

}

render() {
return (

textInComponent

);
}
}

const styles = StyleSheet.create({});
`

SignalR error: Error during negotiation request. Handshake failed

Hi, I'm getting an error
My backend code

    public class FirstHub : Hub, IDisposable
    {

        public string HelloServer(string message)
        {
            Clients.Caller.helloApp("You said:", message, "Server says hello!", (DateTime.Now).ToString(CultureInfo.InvariantCulture));
            return "I responeded by calling helloApp";
        }

        public override Task OnConnected()
        {
            return base.OnConnected();
        }

        public override Task OnReconnected()
        {
            return base.OnReconnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            return base.OnDisconnected(stopCalled);
        }
}

startup.cs

[assembly: OwinStartupAttribute(typeof(Project.Startup))]
namespace Project
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

react native code:

componentDidMount() {
    //This is the server under /example/server published on azure.
    const connection = signalr.hubConnection('https://10.26.xx.xx:xxxx');
    connection.logging = true;

    const proxy = connection.createHubProxy('firstHub');
    //receives broadcast messages from a hub function, called "helloApp"
   proxy.on('helloApp', (argOne, argTwo, argThree, argFour) => {
      console.log('message-from-server', argOne, argTwo, argThree, argFour);
      //Here I could response by calling something else on the server...
    });

    // atempt connection, and handle errors
    connection.start().done(() => {
      console.log('Now connected, connection ID=' + connection.id);

      proxy.invoke('helloServer', 'Hello Server, how are you?')
        .done((directResponse) => {
          console.log('direct-response-from-server', directResponse);
        }).fail(() => {
          console.warn('Something went wrong when calling server, it might not be up and running?')
        });

    }).fail(() => {
      console.log('Failed');
    });

    //connection-handling
    connection.connectionSlow(() => {
      console.log('We are currently experiencing difficulties with the connection.')
    });

    connection.error((error) => {
      const errorMessage = error.message;
      let detailedError = '';
      if (error.source && error.source._response) {
        detailedError = error.source._response;
      }
      if (detailedError === 'An SSL error has occurred and a secure connection to the server cannot be made.') {
        console.log('When using react-native-signalr on ios with http remember to enable http in App Transport Security https://github.com/olofd/react-native-signalr/issues/14')
      }
      console.debug('SignalR error: ' + errorMessage, detailedError)
    });
  }

react native chrome debuger console error log ;

capture

Cannot set property 'createElement' of undefined

I'm getting this issue when try to start connection in disconnected function.

Cannot set property 'createElement' of undefined

The issue is coming on this line of signalr index file

`hubConnectionFunc.start = (...args) => {
window.document.createElement = () => {
return {
protocol,
host
};
};
window.location = {
protocol,
host
};
const returnValue = originalStart.apply(hubConnectionFunc, args);
window.document = undefined;
return returnValue;
};

I'm try to restart connection after disconnected and in app active state. My approach is that when app goes to backend, stop the connection and start connection again when app is active again.

Here is my code to integrate -

  let url = AppConfig.ApiUrl+'signalr';
   let qs = "AuthKey="+userData.authKey;
   const connection = this.connectionSignalR = signalr.hubConnection(url, {
      useDefaultPath: false,
      qs : qs
   });
   connection.logging = true;
   const proxy = connection.createHubProxy('notificationHub');
   //receives broadcast messages from a hub function, called "helloApp"
   proxy.on('realTimeNotify', (message) => {
      // Handling of the real time notification here

   });

  connection.disconnected(() =>  {
       setTimeout((connection) => {
            connection.start();
        }, 3000) // Restart connection after 3 seconds.

  });

  connection.start().done(() => {
    console.log("connection", connection);
    console.log('Now connected, connection ID=' + connection.id);
    connection.error((error) => {
      const errorMessage = error.message;
      let detailedError = '';
      if (error.source && error.source._response) {
        detailedError = error.source._response;
      }
      if (detailedError === 'An SSL error has occurred and a secure connection to the server cannot be made.') {
        console.log('When using react-native-signalr on ios with http remember to enable http in App Transport Security https://github.com/olofd/react-native-signalr/issues/14')
      }
      alert('SignalR error: ' + errorMessage+". "+detailedError);
      connection.stop();
    });
  }).fail(() => {
    console.log('Failed');
  });

  //connection-handling
  connection.connectionSlow(() => {
    console.log('We are currently experiencing difficulties with the connection.')
  });
}

_handleAppStateChange = (nextAppState) => {
if(nextAppState === 'background' && this.connectionSignalR) {
this.connectionSignalR.stop();
} else if(nextAppState === 'active' && this.connectionSignalR){
this.connectionSignalR.start();
}
}`

How to send token or other data

Hi, in the web application I use signalR for angular
(https://www.npmjs.com/package/@aspnet/signalr)

When i connected, I send token, example from web app. (accessTokenFactory)

this.notifyHubConnection = new signalR.HubConnectionBuilder()
 .withUrl(`${ this.apiUrl }hub/messages`, { accessTokenFactory: () => token })
 .build();
this.notifyHubConnection.start().catch((err) => this.hubReconnect());
this.notifyHubConnection.on('OnMessageReceived', (sender, senderID, content) => {...});

This is what my code looks like in a web application, can anyone help me open it in this library?

Replace deprecated dependency ms-signalr-client

This dependency is using a deprecated dependency ms-signalr-client, which is causing a warning message for anyone that uses the dependency:

The problem can be found in jquery.signalR.js on line 429, where the duration is set to 300000ms, well over the react-native setInterval limit of 60000ms.

Clients.Group(ChannelId) does not work when using backplane

Hi,
Im using Redis as backplane for my server which is behind a AWS Load balancer.

The simulated environment as follows:
Clients:
Client 1: Web browser with Signalr JS installed
Client 2: React-native app

Server:
C# Server with Signalr and Signalr Redis installed

When a client join a chat room, it will invoke a server method (JoinChat) and the server will broadcast a message to everyone who is inside the chat, including the one who has just joined.

The server side coding as follows:
await Groups.Add(Context.ConnectionId, chatId); Clients.Group(chatId).addTextFromServer("Joined this chat)";

Client 1 received the message with no issue
Client 2 failed to receive the message

Please advise.

Cannot use websockets on iOS

I've been developing with react-native-signalr for both Android and iOS with the requirement that the connection must be websocket based.

Android works wonderfully. iOS gives me the following crash with react-native log-ios:

Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: Running application "SignalRApp" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: 'posting to', 'http://examplesignalr.com/Example/GetToken'
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: 'Example State', { _rowHasChanged: [Function: rowHasChanged],
	  _getRowData: [Function: defaultGetRowData],
	  _sectionHeaderHasChanged: [Function],
	  _getSectionHeaderData: [Function: defaultGetSectionHeaderData],
	  _dataBlob: { s1: [] },
	  _dirtyRows: [ [] ],
	  _dirtySections: [ true ],
	  _cachedRowCount: 0,
	  rowIdentities: [ [] ],
	  sectionIdentities: [ 's1' ] }
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Error>: [] __nwlog_err_simulate_crash simulate crash already simulated "nw_socket_set_common_sockopts setsockopt SO_NOAPNFALLBK failed: [42] Protocol not available"
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Error>: [] nw_socket_set_common_sockopts setsockopt SO_NOAPNFALLBK failed: [42] Protocol not available, dumping backtrace:
	        [x86_64] libnetcore-856.20.4
	    0   libsystem_network.dylib             0x0000000114219682 __nw_create_backtrace_string + 123
	    1   libnetwork.dylib                    0x0000000114a88932 nw_socket_add_input_handler + 3100
	    2   libnetwork.dylib                    0x0000000114a664f4 nw_endpoint_flow_attach_protocols + 3768
	    3   libnetwork.dylib                    0x0000000114a65511 nw_endpoint_flow_setup_socket + 563
	    4   libnetwork.dylib                    0x0000000114a64270 -[NWConcrete_nw_endpoint_flow startWithHandler:] + 2612
	    5   libnetwork.dylib                    0x0000000114a7f44d nw_endpoint_handler_path_change + 1261
	    6   libnetwork.dylib                    0x0000000114a7ee7c nw_endpoint_handler_start + 570
	    7   libdispatch.dylib                   0x0000000113fa1810 _dispatch_call_block_and_release + 12
	    8   libdispatch.dylib                   0x0000000113fc
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: Client subscribed to hub 'exampleHub'.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: Negotiating with 'http://examplesignalr.com/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22exampleHub%22%7D%5D'.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: webSockets transport starting.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: Connecting to websocket endpoint 'ws://examplesignalr.com/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=eXNnRQNAB6mzAEYevdhfupjUyFargeId5n%2FHWLUwH%2FqlNET7OdK3AVR5TT3YaxLn0AHOY9seRfz7tfxM0vRJnR%2BAVGxT8iIuGkoigNj%2FlJoA6k0W81pLCcbAGuPHTW66&connectionData=%5B%7B%22name%22%3A%22exampleHub%22%7D%5D&tid=4'.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Error>: [] __nwlog_err_simulate_crash simulate crash already simulated "nw_socket_set_common_sockopts setsockopt SO_NOAPNFALLBK failed: [42] Protocol not available"
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Error>: [] nw_socket_set_common_sockopts setsockopt SO_NOAPNFALLBK failed: [42] Protocol not available, dumping backtrace:
	        [x86_64] libnetcore-856.20.4
	    0   libsystem_network.dylib             0x0000000114219682 __nw_create_backtrace_string + 123
	    1   libnetwork.dylib                    0x0000000114a88932 nw_socket_add_input_handler + 3100
	    2   libnetwork.dylib                    0x0000000114a664f4 nw_endpoint_flow_attach_protocols + 3768
	    3   libnetwork.dylib                    0x0000000114a65511 nw_endpoint_flow_setup_socket + 563
	    4   libnetwork.dylib                    0x0000000114a64270 -[NWConcrete_nw_endpoint_flow startWithHandler:] + 2612
	    5   libnetwork.dylib                    0x0000000114a7f44d nw_endpoint_handler_path_change + 1261
	    6   libnetwork.dylib                    0x0000000114a7ee7c nw_endpoint_handler_start + 570
	    7   libdispatch.dylib                   0x0000000113fa1810 _dispatch_call_block_and_release + 12
	    8   libdispatch.dylib                   0x0000000113fc
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: Websocket closed.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: Closing the Websocket.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: webSockets transport failed to connect. Attempting to fall back.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: No fallback transports were selected.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: SignalR error: Error: No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: Failed
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: Stopping connection.
Dec  2 13:18:40 Humboldt-Mac-Mini SignalRApp[89427] <Notice>: [13:18:40 GMT+0000 (GMT)] SignalR: Fired ajax abort async = true.

Here is the snippet of code used to cause this crash:

var connection = signalr.hubConnection(this.getUrl());
connection.logging = true;

exampleProxy = connection.createHubProxy('exampleHub');

connection.start({transport: ['webSockets']}).done(() => { 
    console.log('Now connected, connection ID=' + connection.id); 
    exampleProxy.invoke("SomeMethod").done((r) => {
      console.log("SomeMethod result",r);
    });
}).fail(() => {
    console.log('Failed'); 
});

Unfortunately, falling back to long-polling isn't an option for us.

not connection SignalR error: undefined

signals system => html page connection to signalr no problem alone react-native-signalr plugin there is an error

Back end code

[assembly: OwinStartup(typeof(Statistics.Startup))]
namespace Statistics
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
           
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
        }
    }
}

namespace Statistics
{
    [HubName("dataHub")]
    public class DataHub : Hub
    {
        public void Send(object obj)
        {
            Clients.All.broadcastMessage(obj);
        }
    }
}

html code

<script src="Scripts/jquery-1.6.4.js"></script> <script src="Scripts/jquery.signalR-2.2.1.js"></script> <script src="signalr/hubs"></script>

$(function() {
        var chat = $.connection.dataHub;
         chat.client.broadcastMessage = function ( message) {
            console.dir(message)
        };

        $.connection.hub.url = "http://myserverurl/signalr/hubs";
        $.connection.hub.start().done(function() {
                 chat.server.send('test sample');
        });
    });

html connection no problem

react-native code

import signalr  from "react-native-signalr";


componentDidMount(){



        var connection = signalr.hubConnection('http://myserverurl/signalr/hubs');

        connection.logging = true;

        var proxy = connection.createHubProxy('dataHub');
 
        proxy.on('broadcastMessage', (message) => {
            console.log(message);

        });



            connection.start().done(() => {
                console.log('Now connected, connection ID=' + connection.id);
            }).fail(() => {
                console.log('Failed');
            });



        console.log(connection.connectionState)

            connection.connectionSlow(function () {
                console.log('We are currently experiencing difficulties with the connection.')
            });

            connection.error(function (error) {
                console.log('SignalR error: ' + error)
            });

    }

react native chrome debuger console error log ;

ekran resmi 2016-11-25 10 50 17

Example project can you share Help Me :)

$.param issue

It lacks of method $.param when I am using qs , and also I saw you guys added a commit in file signalr-jquery-polyfill.js, could you please release it first, thanks in advance.
cors: true

+    },
+    param: (source) => {
+      let array = []
+      for(var key in source) {
+        array.push(encodeURIComponent(key) + "=" + encodeURIComponent(source[key]))
+      }
+      return array.join("&")
     }

get 'undefined' from server in invoke

proxy.invoke(...) .done((directResponse) => { console.log('direct-response-from-server', directResponse); // directResponse is always 'undefined'!! but server will do that func correctly }).fail((e) => { console.warn('Something went wrong when calling server, it might not be up and running?: ' + e) });

Error: Method GET must not have a request body

I can't use the function:

connection.start().done(() => {

as shown in the example.

This error occurs: Method GET must not have a request body.

"react": "16.0.0-beta.5"
"react-native": "0.49.3"
"react-native-signalr": "^1.0.5"

How is reconnection handled?

I've done some testing where I shut down the signalr server API then restart it again. But the client hub doesn't seem to reconnect properly. In fact I actually get the reconnected event triggered while the server is still off. Is there anything special I need to do?

IOS - SignalR Connection break when app move in background.

Implementing SignalR in IOS React native app for Remote push notification.
I have an issue when app move in the background then SignalR connection breaked.
When App again in the foreground that working properly.

Please help for that.

what is best way for catching server errors without red screen of death

Awesome module,thank you very much for your work!
I have a question-what is the best way for catching server errors without red screen of death?

connection.start().done(()=>{
  connection.error( error => {
      //here i get the error from the server
    /*console.log(error.message)-->`it has exceeded the inactivity timeout of 50000 ms. Stopping the connection.` 
    but I can't handle this error here, because the red screen from simulator shoots immediately-`cannot read property supportsKeepAlive of null`*/
  });
})

Thank you!

This browser doesn't support SSE.

I'm working with Android simulator, and I'm receiving the error:

error signalr

Additional Info:
Windows 10 64bits
Android: Nexus_5X_API_25_x86 - Android 6.0
Node: 3.10.10
React-native: 0.41.2
React: 15.4.2
react-native-signalr: 1.0.0

sometimes got an error 'No transport could be initialized successfully...'

It connected failed sometimes,but it worked sometimes.
And I got this error:
"Error: No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization."

This is my code:
connection.start({transport: 'webSockets'}).done(() => {
console.log('success');
}).fail(() => {
console.log('error')
});
connection.error(function(error){
console.log(error)//this prints that error.
});

Problems with signalr transportation

Hi,

I am working on a simple POC using react-native-signalr. However, when I attempt to connect to my hub (ASP.NET Signalr hosted on my own IIS), I got an exception saying "No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization". I believe some setting could have gone wrong. How do I fix this problem?

Appreciate some kind help.

Response from proxy.invoke promise not getting returned

Thanks for the work on this. One issue I'm experiencing is when making a call to the server with proxy.invoke, the response that I'm sending from the server back to client doesn't seem to be getting returned via the promise.

For example:

        let messagePromise = proxy.invoke('messageToServer', 'hej');
        messagePromise.done((response) => {
            console.log ("response", response');
        }).fail(function (error) {
            console.log('Invocation of NewContosoChatMessage failed. Error: ' + error);
        });

When I log out the response from the promise, I'm seeing a different object that looks something like this:

{state: Object, connection: h…n.fn.init, hubName: "hubname", _: Object, events: Object}

connection failure issue

When there is no internet connection and a connection.start() is attempted .fail() fires as expected, but the error is propogated out after exiting the fail() closure and we end up with the familiar RN red screen. Any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.