Giter VIP home page Giter VIP logo

react-websocket's Introduction

react-websocket contributions welcome FOSSA Status

react-websocket is a easy-to-use React component for websocket communications.

Help Wanted

Things here are running very slowly as I have a lot of other stuff to take care at the moment so please don't be upset if I don't answer your question or if a PR sits unreviewed for a few days or weeks. Anyone interested in helping it move faster can help by submitting or reviewing PR's and answering each other's questions.

Installing

npm install --save react-websocket

Usage

  import React from 'react';
  import Websocket from 'react-websocket';

  class ProductDetail extends React.Component {

    constructor(props) {
      super(props);
      this.state = {
        count: 90
      };
    }

    handleData(data) {
      let result = JSON.parse(data);
      this.setState({count: this.state.count + result.movement});
    }

    render() {
      return (
        <div>
          Count: <strong>{this.state.count}</strong>

          <Websocket url='ws://localhost:8888/live/product/12345/'
              onMessage={this.handleData.bind(this)}/>
        </div>
      );
    }
  }

  export default ProductDetail;

Properties

url

required The url the websocket connection is listening to.

onMessage

required The callback called when data is received. Data is JSON.parse'd

onOpen

The callback called when the connection is successfully opened.

onClose

The callback called when the connection is closed either due to server disconnect or network error.

debug

default: false Set to true to see console logging

reconnect

default: true

accelerated reconnection time

License

FOSSA Status

react-websocket's People

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  avatar  avatar

react-websocket's Issues

install is error

PS E:\react-websocket> yarn start
yarn run v1.5.1
$ cross-env NODE_ENV=development node server.js
E:\react-websocket\node_modules\webpack-dev-server\lib\Server.js:131
const { compile, invalid, done } = compiler.hooks;
^

TypeError: Cannot destructure property compile of 'undefined' or 'null'.
at addHooks (E:\react-websocket\node_modules\webpack-dev-server\lib\Server.js:131:49)
at new Server (E:\react-websocket\node_modules\webpack-dev-server\lib\Server.js:144:5)
at Object. (E:\react-websocket\server.js:5:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)

npm test results in "ReferenceError: WebSocket is not defined"

I'm using react-websocket 1.1.6

This is working in development, but when running npm test on my project I see...

    ReferenceError: WebSocket is not defined

      at new Websocket (node_modules/react-websocket/build/index.js:89:16)
      at node_modules/react/lib/ReactCompositeComponent.js:294:18
      ...

The line in question is...

ws: new WebSocket(this.props.url),

Should ws be a dev dependency?

onMessage fired twice when receiving Json data

When receiving a message that is a stringified json object the onMessage function is called twice. First with the string version and then with the string parsed to a JSON object.

Server setup:

var server = require('websocket').server;
var socket = new server({
    httpServer: http.createServer().listen(8008),
});
socket.on('request', function(request) {
    const connection = request.accept(null, request.origin);
    connection.send("{\"test\":\"message\"}");
})

Client setup


const WebsocketManagerFunc = () => {
  const messageReceived = (data) => {
    console.log('received data');
    console.log(data);
    console.log(typeof data);
  };

  return (
    <Websocket
      url={`ws://localhost:8008/`}
      onMessage={messageReceived}
    />
  );
};

console log

Websocket connected
received data
{"test":"message"}
string
received data
{test: "message"}
object

please update example/server.py

Hello,
Could you please update example/server.py for the latest python environment?
Otherwise, the following error occurred:

$ python3 example/server.py 
Traceback (most recent call last):
  File "example/server.py", line 29, in <module>
    class WebSocketHandler(tornado.websocket.WebSocketHandler):
  File "example/server.py", line 35, in WebSocketHandler
    @tornado.gen.engine
AttributeError: module 'tornado.gen' has no attribute 'engine'
$
$ pip3 list | grep -e appdirs -e packaging -e pyparsing -e six -e tornado
appdirs             1.4.3
packaging           19.2 
pyparsing           2.4.4 
six                 1.13.0 
tornado             6.0.3 

onClose is not being fired

I am not getting onClose events via WebSocket. onOpen events work fine. I have built a test websocket server via node.js that I am starting and stopping.

 <Websocket url='ws://localhost:3132/btc/' 
             debug={true}
             protocol="echo-protocol"  
             onMessage={this.handleData.bind(this)}
             reconnect={true}
             onClose={this.handleClose.bind(this)}
             onOpen={this.handleOpen.bind(this)}
        />

Console printout:

bundle.js:103859 WebSocket connection to 'ws://localhost:3132/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
(anonymous) @ bundle.js:103859
bundle.js:103825 Websocket disconnected

I did a npm install today, and am using the redux-minimal.js.org starter kit.

I think this is a bug.

Cant send POST data through websocket

I need to send an array of simple objects to the websocket, and as far as I know this is not possible since the websocket url is GET only.

Is there a way I'm missing to send more complex params through the URL or would it be a potential feature to add?

Changing url does not update websocket url

Changing the url after component has mounted does not cause the websocket to update

Example:

const WebsocketDemo = ({ url }) => {
  const [message, setmessage] = useState('');
  const [urlVal, seturlVal] = useState(url);
  const handleData = (data) => {
    setmessage(data);
  };

  return (
    <div>
      <p>
        <input type="text" value={urlVal} onChange={(e) => { seturlVal(e.target.value) }} />
      </p>

      <Websocket
        url={urlVal}
        onMessage={handleData}
      />
    </div>
  );
};

New Instance on every render() ?

Does this mean that if I call setState({}), it will cause render and the Websocket tag will happen again making the socket start a new connection?

onClose never called ?!

Hi, yesterday I used react-websocket and it works well but when I do this :

<Websocket 
          url='ws://localhost:8080/' 
          onMessage={this.handleData.bind(this)}
          onClose={this.handleClose.bind(this)}
          onOpen={this.handleOpen.bind(this)}/>

onOpen works, onMessage works but onClose doesn't works.
I go into the module to see index.jsx file and I see :

websocket.onclose = () => {
    this.logging('Websocket disconnected');
    if (typeof this.props.onClose === 'function') this.props.onClose();
    if (this.shouldReconnect) {
        let time = this.generateInterval(this.state.attempts);
        this.timeoutID = setTimeout(() => {
            this.setState({attempts: this.state.attempts+1});
            this.setState({ws: new WebSocket(this.props.url, this.props.protocol)});
            this.setupWebsocket();
        }, time);
    }
}

So it will works but in the build file, the

if (typeof _this.props.onClose !== 'undefined') _this.props.onClose();

is missing.
On Master branch, the build file has this line so could you add new tag to npm Please ? Because for now I need to add this line in the build file.

Thanks.

How to send?

How do you reference the websocket to send and control?
thx

Interval

How to set interval for receiving data?

Security support

This is a nice component.

I'd like to see options expanded so we could pass an Auth token in the header, so connections are authorized.

onError

Is there an implementation of onError in this?

state.attempts is never reset

In the situation where periodic disconnections are expected, the component will eventually always use the max retry backoff, because a successful reconnection never resets state.attempts.

I'll happily put together a pull request if you'd like, or just add this snippet

websocket.onopen = () => {
      this.logging('Websocket connected')
      this.setState({ attempts: 1 }) // Add this line so that reconnecting resets the retry cooloff.
...

Doesn't reconnect

Using react 15.x

If my server running the websocket is disconnected, it doesn't attempt to reconnect at all.
With debug mode on, the last message is just Websocket disconnected.

Any ideas?

Doesnt Install

Pretty sure this no longer installs / works - lots of errorsradynapier:~/workspace (devel) $ npm install --save react-websocket
npm WARN package.json [email protected] No repository field.
|

[email protected] install /home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/utf-8-validate
node-gyp rebuild

make: Entering directory /home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/utf-8-validate/build' CXX(target) Release/obj.target/validation/src/validation.o In file included from ../src/validation.cc:15:0: ../node_modules/nan/nan.h:261:25: error: redefinition of ‘template<class T> v8::Local<T> _NanEnsureLocal(v8::Local<T>)’ NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) { ^ ../node_modules/nan/nan.h:256:25: error: ‘template<class T> v8::Local<T> _NanEnsureLocal(v8::Handle<T>)’ previously declared here NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Handle<T> val) { ^ ../node_modules/nan/nan.h:661:13: error: ‘node::smalloc’ has not been declared , node::smalloc::FreeCallback callback ^ ../node_modules/nan/nan.h:661:35: error: expected ‘,’ or ‘...’ before ‘callback’ , node::smalloc::FreeCallback callback ^ ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanNewBufferHandle(char*, size_t, int)’: ../node_modules/nan/nan.h:665:50: error: ‘callback’ was not declared in this scope v8::Isolate::GetCurrent(), data, length, callback, hint); ^ ../node_modules/nan/nan.h:665:60: error: ‘hint’ was not declared in this scope v8::Isolate::GetCurrent(), data, length, callback, hint); ^ ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanNewBufferHandle(const char*, uint32_t)’: ../node_modules/nan/nan.h:672:67: error: call of overloaded ‘New(v8::Isolate*, const char*&, uint32_t&)’ is ambiguous return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); ^ ../node_modules/nan/nan.h:672:67: note: candidates are: In file included from ../src/validation.cc:10:0: /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:31:40: note: v8::MaybeLocal<v8::Object> node::Buffer::New(v8::Isolate*, v8::Local<v8::String>, node::encoding) <near match> NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, ^ /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:31:40: note: no known conversion for argument 3 from ‘uint32_t {aka unsigned int}’ to ‘node::encoding’ /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:43:40: note: v8::MaybeLocal<v8::Object> node::Buffer::New(v8::Isolate*, char*, size_t) <near match> NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, ^ /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:43:40: note: no known conversion for argument 2 from ‘const char*’ to ‘char*’ In file included from ../src/validation.cc:15:0: ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanNewBufferHandle(uint32_t)’: ../node_modules/nan/nan.h:676:61: error: could not convert ‘node::Buffer::New(v8::Isolate::GetCurrent(), ((size_t)size))’ from ‘v8::MaybeLocal<v8::Object>’ to ‘v8::Local<v8::Object>’ return node::Buffer::New(v8::Isolate::GetCurrent(), size); ^ ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanBufferUse(char*, uint32_t)’: ../node_modules/nan/nan.h:683:12: error: ‘Use’ is not a member of ‘node::Buffer’ return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); ^ make: *** [Release/obj.target/validation/src/validation.o] Error 1 make: Leaving directory/home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/utf-8-validate/build'
gyp ERR! build error
gyp ERR! stack Error: make failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/home/ubuntu/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.2.0-c9
gyp ERR! command "/home/ubuntu/.nvm/versions/node/v4.2.1/bin/node" "/home/ubuntu/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/utf-8-validate
gyp ERR! node -v v4.2.1
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok

[email protected] install /home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/bufferutil
node-gyp rebuild

make: Entering directory /home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/bufferutil/build' CXX(target) Release/obj.target/bufferutil/src/bufferutil.o In file included from ../src/bufferutil.cc:16:0: ../node_modules/nan/nan.h:261:25: error: redefinition of ‘template<class T> v8::Local<T> _NanEnsureLocal(v8::Local<T>)’ NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) { ^ ../node_modules/nan/nan.h:256:25: error: ‘template<class T> v8::Local<T> _NanEnsureLocal(v8::Handle<T>)’ previously declared here NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Handle<T> val) { ^ ../node_modules/nan/nan.h:661:13: error: ‘node::smalloc’ has not been declared , node::smalloc::FreeCallback callback ^ ../node_modules/nan/nan.h:661:35: error: expected ‘,’ or ‘...’ before ‘callback’ , node::smalloc::FreeCallback callback ^ ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanNewBufferHandle(char*, size_t, int)’: ../node_modules/nan/nan.h:665:50: error: ‘callback’ was not declared in this scope v8::Isolate::GetCurrent(), data, length, callback, hint); ^ ../node_modules/nan/nan.h:665:60: error: ‘hint’ was not declared in this scope v8::Isolate::GetCurrent(), data, length, callback, hint); ^ ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanNewBufferHandle(const char*, uint32_t)’: ../node_modules/nan/nan.h:672:67: error: call of overloaded ‘New(v8::Isolate*, const char*&, uint32_t&)’ is ambiguous return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); ^ ../node_modules/nan/nan.h:672:67: note: candidates are: In file included from ../src/bufferutil.cc:10:0: /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:31:40: note: v8::MaybeLocal<v8::Object> node::Buffer::New(v8::Isolate*, v8::Local<v8::String>, node::encoding) <near match> NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, ^ /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:31:40: note: no known conversion for argument 3 from ‘uint32_t {aka unsigned int}’ to ‘node::encoding’ /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:43:40: note: v8::MaybeLocal<v8::Object> node::Buffer::New(v8::Isolate*, char*, size_t) <near match> NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, ^ /home/ubuntu/.node-gyp/4.2.1/include/node/node_buffer.h:43:40: note: no known conversion for argument 2 from ‘const char*’ to ‘char*’ In file included from ../src/bufferutil.cc:16:0: ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanNewBufferHandle(uint32_t)’: ../node_modules/nan/nan.h:676:61: error: could not convert ‘node::Buffer::New(v8::Isolate::GetCurrent(), ((size_t)size))’ from ‘v8::MaybeLocal<v8::Object>’ to ‘v8::Local<v8::Object>’ return node::Buffer::New(v8::Isolate::GetCurrent(), size); ^ ../node_modules/nan/nan.h: In function ‘v8::Local<v8::Object> NanBufferUse(char*, uint32_t)’: ../node_modules/nan/nan.h:683:12: error: ‘Use’ is not a member of ‘node::Buffer’ return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); ^ make: *** [Release/obj.target/bufferutil/src/bufferutil.o] Error 1 make: Leaving directory/home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/bufferutil/build'
gyp ERR! build error
gyp ERR! stack Error: make failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/home/ubuntu/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.2.0-c9
gyp ERR! command "/home/ubuntu/.nvm/versions/node/v4.2.1/bin/node" "/home/ubuntu/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/ubuntu/workspace/node_modules/react-websocket/node_modules/ws/node_modules/bufferutil
gyp ERR! node -v v4.2.1
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN optional dep failed, continuing [email protected]
npm WARN optional dep failed, continuing [email protected]
[email protected] node_modules/react-websocket
└── [email protected] ([email protected], [email protected])

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.