Coder Social home page Coder Social logo

gcrabtree / react-native-socketio Goto Github PK

View Code? Open in Web Editor NEW
152.0 7.0 56.0 115 KB

Not Maintained! A React Native wrapper for both the Swift and Java Socket.Io clients.

License: MIT License

Swift 87.76% Objective-C 0.55% JavaScript 1.09% Java 10.61%

react-native-socketio's Introduction

A React Native wrapper for the Socket.io Library

Please note that this hasn't been maintained for ages. If someone would like to bring back upto speed, let me know. -Greg

This project was forked from Kirkness' React Native Swift Socket.Io project found here

Note: We are working on the following items:

  • Reviewing Pull requests and seeing if they are pertinent.
  • Making the project compatible with RN .33
  • Making the project XCode 8 compatible.
  • Upgrading to Swift 2.3
  • Creating a simple test project

This project now supports both iOS and Android using the same JS calls.

Example

Kirkness added a super simple example app to /examples, copy and paste to your index.ios.js.

/**
 * Pass in an optional config obj, this can include most of the
 * standard props supported by the swift library
 */
var socketConfig = { path: '/socket' };
var socket = new SocketIO('localhost:3000', socketConfig);

// Connect!
socket.connect();

// An event to be fired on connection to socket
socket.on('connect', () => {
    console.log('Wahey -> connected!');
});

// Event called when 'someEvent' it emitted by server
socket.on('someEvent', (data) => {
    console.log('Some event was called, check out this data: ', data);
});

// Called when anything is emitted by the server
socket.onAny((event) => {
    console.log(`${event.name} was called with data: `, event.items);
});

// Manually join namespace. Ex: namespace is now partyRoom
socket.joinNamespace('partyRoom')

// Leave namespace, back to '/'
socket.leaveNamespace()

// Emit an event to server
socket.emit('helloWorld', {some: 'data'});

//Disconnect from server
socket.disconnect();

// Reconnect to a closed socket
socket.reconnect();

Constructor

Requires: host - example: 'localhost:3000'

Optional: config - JSON object comprising any of the options listed below.

Config

  • Please note that the Android version does not support all of these options yet. It's very much a work in progress.
  • connectParams: Any Object - Any data to be sent with the connection.
  • reconnects: Boolean Default is true
  • reconnectAttempts: Int Default is -1 (infinite tries)
  • reconnectWait: Number Default is 10
  • forcePolling: Boolean Default is false. true forces the client to use xhr-polling.
  • forceWebsockets: Boolean Default is false. true forces the client to use WebSockets.
  • nsp: String Default is "/". Connects to a namespace.
  • log: Bool If true socket will log debug messages. Default is false.
  • path: String - If the server uses a custom path. ex: "/swift". Default is ""

Not supported yet but easy enough to implement.

  • cookies: [NSHTTPCookie]? An array of NSHTTPCookies. Passed during the handshake. Default is nil.
  • sessionDelegate: NSURLSessionDelegate Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.

Methods

  • connect - Connect to socket
  • on - Add event handler to socket
    • @param - String - event name
    • @param - Function - callback
  • onAny - Add event handler to any event
    • @param - Function - callback
  • emit - Emit an event to server
    • @param - String - Event name
    • @param - Anything - Data to be sent
  • disconnect - Close the connection
  • reconnect - Reconnect to a closed connection
  • joinNamespace - Manually join namespace
    • @param - String - Namespace
  • leaveNamespace - Leave namespace, back to '/'

Known issues

  • Would rather this in an xcode framework but run into non-modular header issue.
  • Android needs more configuration option support.
  • Both implementations need unit testing.

Install

  • Run in your project:
$ npm install react-native-socketio

iOS

  • Note as of May 19, 2016 that the path to the ios components has been moved from root to the /ios folder.
  • Open up your project in xcode and right click the package.
  • Click Add files to 'Your project name'
  • Navigate to /node_modules/react-native-socketio/ios/RNSwiftSocketIO
  • Click 'Add'
  • Click your project in the navigator on the left and go to build settings
  • Search for Objective-C Bridging Header
  • Double click on the empty column
  • Enter ../node_modules/react-native-socketio/ios/RNSwiftSocketIO/SocketBridge.h
  • Search for Header Search Paths
  • Double Click on the column (likely has other search paths in it already)
  • Enter this text at the bottom of the column $(SRCROOT)/../node_modules/react-native-socketio/ios/RNSwiftSocketIO

Android

  1. In android/setting.gradle

    ...
    include ':SocketIo'
    project(':SocketIo').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-socketio/android')
    
  2. In android/app/build.gradle

    ...
    dependencies {
        ...
        compile project(':SocketIo')
    }
    
  3. Register module (in MainActivity.java)

    import com.gcrabtree.rctsocketio.SocketIoPackage;  // <--- import
    
    public class MainActivity extends ReactActivity {
      ......
    
      @Override
      protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new VectorIconsPackage(),
          new OrientationPackage(this),
          new SocketIoPackage()   // <--- Add here!
      );
    }
    
      ......
    
    }
    

react-native-socketio's People

Contributors

gcrabtree 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

react-native-socketio's Issues

Getting error in installation

In android/setting.gradle

...
include ':SocketIo'
project(':SocketIo').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-socketio/android')
In android/app/build.gradle

...
dependencies {
...
compile project(':SocketIo')
}

After that getting below error

Isssue

emit an Array

is it not possible to emit an Array?

Code looks like:
socket.emit('foo', {array: [1,2]})

screenshot_20160820-202142

iOS installation problem

  • Navigate to /node_modules/react-native-socketio/ios/RNSwiftSocketIO
  • Click 'Add'
  • Click your project in the navigator on the left and go to build settings
  • Search for Objective-C Bridging Header

What is Objective-C Bridging Header? I can't find it here. I am not familiar with Xcode so could you please help me?

Android socket event is global,and open new socket the old event is still there

image
first I just close socket in componentWillUnmount,but when I navigatior to this Sence the register function will be called twice, then I navigator.pop and navigator.push the sence again, the register function will be called 3 times. It seems the register function was storage at global queue!!!
I solve my problem: register 'do nothing function ' at componentWillUnmount,if not myTest event fun,have call setState,it will lead to excpetion:setState Can only update a mounted or mounting component.

Do I make myself clear?

Sending query strings with connect()

This feature seems to be missing from this package. I checked the code and the connect() method doesn't take any parameters.

With pure socket.io you can do something like this:
io.connect(socketUrl, {query: "email=" + store.get('profile').email + "&type=pc"})

I tried passing the query string like this:
new SocketIO(socketUrl, {query: "[email protected]&type=web"});

The above doesn't work though. I'm not able to get the query string on my server.

SocketIoReadableNativeMap.java constructor not defined

eact-native-socketio/android/src/main/java/com/gcrabtree/rctsocketio/SocketIoReadableNativeMap.java:17: 错误: 无法将类 ReadableNativeMap中的构造器 ReadableNativeMap应用到给定类型;

image
because the super constructor is protect,change like below is ok,
image
hope help.

React Native 0.29+ compatibility

There is some issues with Socket.swift file which is deprecated with the newest version of RN and Swift, this sometimes causes crashes in development environment and prevents smooth debugging. Also I had many issues to install the libraries with Xcode. Maybe it's a good idea to use RNPM library to link it automatically?

constructor ReadableNativeMap in class ReadableNativeMap cannot be applied to given types;

When integrating this module to my android project i get the error code as in the title mentioned.

..../React/ChatTest/node_modules/react-native- socketio/android/src/main/java/com/gcrabtree/rctsocketio/SocketIoReadableNativeMap.java:16: error: constructor ReadableNativeMap in class ReadableNativeMap cannot be applied to given types;
public class SocketIoReadableNativeMap extends ReadableNativeMap {
   ^
  required: HybridData
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

Android XHR polling

I am trying to connect a react-native android app with a chat server that only allows polling.
However, I can't seem to establish a connection with the below implementation.
is XHR polling allowed react native?

var socketConfig = { transports: ['polling'], jsonp: false, forcePolling: true }; this.socket = new SocketIO('localhost:3000' ,socketConfig);

undefined is not an object (evaluating this.sockets.initialize)

this.socket = new SocketIO('http://myserver.com:3000/', {secure: true}); this.socket.on('connect', () => { this.socket.emit('authentication', { token: this.state.valid, id_user: this.state.id });

I`m using react-native 0.42
getting this error just in iOs

react-native 0.39.2

master/android/app/src/main/java/com/boardgameexample/MainActivity.java:25: 错误: 方法不会覆盖或实现超类型的方法
@OverRide
^
/Users/allen/Downloads/react-cross-platform-boardgame-example-master/android/app/src/main/java/com/boardgameexample/MainActivity.java:34: 错误: 方法不会覆盖或实现超类型的方法
@OverRide
^
2 个错误

node_modules bundles/default/AndroidManifest.xml FileNotFoundException

I got this issue with React Native 0.48
ADK 25 for Android 7.1.1
Build tool 25.0.1

Error:Execution failed for task ':app:processDebugManifest'.

com.android.manifmerger.ManifestMerger2$MergeFailureException: java.io.FileNotFoundException: /home/vietvh/Workspace/Projects/Flockface/src/node_modules/react-native-socketio/android/build/intermediates/bundles/default/AndroidManifest.xml (No such file or directory)

react-native-socketio android node_modules bundles/default/AndroidManifest.xml FileNotFoundException

Not compatible with react-native init?

Objective-C Bridging Header doesn't exist. After Googling it, it seems I need to create a new build target with Swift as the language choice. But will this break my React stuff?

How to fix: opening import file for module 'Swift': Permission denied

Hi,

I have problem when compiling the project using this library, it show the error:

  • opening import file for module 'Swift': Permission denied

Does anyone has any suggestion?

Before that I had another problem “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift...
I fixed by turn "Use Legacy Swift Language Version" to YES. Does it has any impact with above problem?

Thanks in advance.

can't parse String type,when node call emit('eventName', JSON.stringify({name:'hj',age:23}));

I use nodejs as server,when I call emit('change',{name:'hj',age:23}); is ok, client can get the obj,
but when I call emit('change',JSON.stringify({name:'hj',age:23})); I get always get null.
the way solved the problem.
change the code below the file:(the red code is add)
.../node_modules/react-native-socketio/android/src/main/java/com/gcrabtree/rctsocketio/SocketIoJSONUtil.java
image

Event created in Android device shown as Birthday on Calendar and after sometime it disappears

I am creating event in Android device but the title always shown as Birthday and no notes and other fields appear like alarm or startdate and enddate on Gmail calendar.

Also the created event disappears from calendar in some seconds. This was not happening until yesterday.

RNCalendarEvents.saveEvent('Call User', { notes: 'Test Note', description: 'Test Note', startDate: <start date>, endDate: <end date>, alarms: [ { date: 5 } ] });

Removing listeners

There is no removing of listeners which is critical in some points. Maybe use removeAllHandlers() and off() methods from the wrapped libraries?

Android installation issue

error: package com.github.gcrabtree.rctsocketio does not exist
import com.github.gcrabtree.rctsocketio.SocketIoPackage;

The correct location of the package (in MainActivity.java) is:
import com.gcrabtree.rctsocketio.SocketIoPackage;

Where to import SocketIO from?

Sorry if this seems trivial, but I can't figure it out: Where do you import SocketIO from in the example?

var socket = new SocketIO('localhost:3000', socketConfig);

If I do

import SocketIO from 'react-native-socketio'

I get "Cannot read property 'initialize' of undefined" error.

Compile failed with React Native 0.32

Compile failed with the following message when I tried to build for Android :

Project_Path\node_modules\react-native-socketio\android\src\mai n\java\com\gcrabtree\rctsocketio\SocketIoReadableNativeMap.java:16: error: constru ctor ReadableNativeMap in class ReadableNativeMap cannot be applied to given types ;
public class SocketIoReadableNativeMap extends ReadableNativeMap {
^
required: HybridData
found: no arguments
reason: actual and formal argument lists differ in length
1 error
:SocketIo:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':SocketIo:compileDebugJavaWithJavac'.

    Compilation failed; see the compiler error output for details.

React Native Version: 0.32
Operating system: Win 7

Swift 3

@gcrabtree: You wrote on a couple of days ago that you're currently working on upgrading to Swift 2.3. Will you also support Swift 3?

@JohnKim, @algesten: Do you already have a fork working with Swift 3?

self.bridge.eventDispatcher().sendDeviceEventWithName

when i refresh js ,it crash , the bug is in onAnyEventHandler -> self.bridge.eventDispatcher().sendDeviceEventWithName("socketEvent",body: ["name": sock.event, "items": items])

it report EXC-BAD-INSTRUCTION(CODE=EXCI386_INVOP,subcode=0x0)

Can't find variable: SocketIO

I did everything as in instruction and gettin' Can't find variable: SocketIO
"react": "15.4.1",
"react-native": "0.39.2",

error: method do es not override or implement a method from a supertype

...\src\main\java\com\gcrabtree\rctsocketio\SocketIoPackage.java:28: error: method do es not override or implement a method from a supertype
@OverRide
^

public class SocketIoPackage implements ReactPackage {

    public SocketIoPackage() {
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Arrays.<NativeModule>asList(
                new SocketIoModule(reactContext)
        );
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Arrays.asList();
    }
}

android is ok,but ios error

xx/node_modules/react-native-socketio/ios/RNSwiftSocketIO/SocketBridge.h:12:9: error: 'RCTBridge.h>' file not found
Has anyone encountered it?please help me !

[Support Request] Multiple client problem

@gcrabtree ,
This plugin was great, but when I created 2 client in the same app, there was a problem with incoming message.

Situation:

  • I have 1 server which run 2 socket.io app: 1 for notification, 1 for messaging, both use the same event name 'message' to listen for message from client.
  • In my app, I have 2 client: 1 for notification, 1 for messaging, using you plugin.

The problem is, when there was 1 message sent from 1 of the servers, both client receive that message :(

That make me a headache a lot.
Can you please help me figure out what cause this and how to fix it?

Thanks.

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.