使用WebSocket.js作为JS模块代替React组件

时间:2017-08-14 12:06:10

标签: javascript reactjs websocket

我有一个定义如下的Websocket.JS:

   class Websocket extends Component {

      constructor(props) {
        super(props);
        const url = Config.ws + Config.baseEndPoint + Config.pen;
        const protocol = this.props.protocol;
        const doesLogging = (this.props.doesLogging === "true");
        this.state = {"url": url,
                      "protocol": protocol,
                      "socket": new WebSocket(url, protocol),
                      "doesLogging": doesLogging};
      };

      onOpen() {

      }

      onMessage(msg) {

      }

      onClose() {

      }

      render() {
        return (
          <div id="websocket"></div>
        );
      }

    }

    export default Websocket;

并在app.js中使用它:

    import Websocket from './services/websocket';
    <Websocket handleMessage={(msg) => this.messageReceived(msg.data)} />

但是,我想将它用作模块而不像HTML元素那样表示。有可能我能做到吗?

1 个答案:

答案 0 :(得分:0)

我不认为必须通过使用任何类型的UI库在代码中呈现通过websockets进行的交互。因此:

   class YourWebsocket{

      constructor(protocol, url, enableLogging) {
        this.url = url;
        this.protocol = protocol;
        this.loggingEnabled = enableLogging;
        this.socket = new WebSocket(url, protocol);
        this.socket.onopen = (ev) => this.onOpen();
        // Assign more handlers here
      }

      onOpen() {

      }

      onMessage(msg) {

      }

      onClose() {

      }

      send(data, callback)
      {
        var listener = (e) =>
        {
            var reply = e.data;

            if(replyIsForOurRequest) //Here you should come up with the logic to decide if this is reply for your request
            {
                this.socket.removeEventListener("message", listener);
                callback(reply);                
            }
        };

        this.socket.addEventListener("message", listener);
        this.socket.send(data);
      }
    }

    export default YourWebsocket;

在你的app.js componentDidMount方法的某个地方:

import YourWebsocket from './services/YourWebsocket';

class App extends React.Component
{
    componentDidMount()
    {
        this.webSocket = new YourWebsocket();
        //...
    }
}