2016-06-30 4 views
6

Websocketベースのクライアント/サーバーアプリケーションを作成したいと思います。そこでは、クライアントを待っているノードjs websocketサーバーが作成されています。今私は反応js websocketクライアントを作成したいと思います。私はWebSocketとして反応するjsを使用しています。なぜなら、サーバーが単純なテキストメッセージとして送信する要素を連続的にレンダリングする必要があるからです。react jsがwebsocketクライアントとしてどのように機能しますか?

私はwebsocketクライアントとしてreact jを実装することに打ち勝ちました。それはどのようにのWebSocketクライアントとして動作するはずですし、どのようにそれはちょうどこのようなWebSocketサーバーにリクエストを送信します:

'ws://localhost:1234' 

私はのWebSocketクライアントの詳細を知りたいとも、この問題を解決したいですか?多くのオーバーヘッドなしだから、

+0

私はあなたが他の質問をする前に、このhttps://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applicationsを読むことをお勧めしたいです。 –

+0

ok ...このページを読む...しかし、私は反応jsでそれを実装したい...私の質問は、どのように反応jsでwebsocketクライアントを実装することができますか? – kit

+0

これは音チュートリアルのようですhttps://www.alfresco.com/blogs/devops/2015/07/07/how-i-probably-over-simplified-integrated-web-sockets-messaging-and-reactjs-components/ –

答えて

12

非常に基本的な例では2つのことが必要になります。

  1. コンポーネントの状態を更新するコネクションに接続

  2. イベントリスナーをのWebSocketを参照してコンポーネント メッセージが到着

デモ:http://jsfiddle.net/69z2wepo/47360/

const Echo = React.createClass({ 
    getInitialState(){ 
    return { messages : [] } 
    }, 
    componentDidMount(){ 
    // this is an "echo" websocket service for testing pusposes 
    this.connection = new WebSocket('wss://echo.websocket.org'); 
    // listen to onmessage event 
    this.connection.onmessage = evt => { 
     // add the new message to state 
     this.setState({ 
     messages : this.state.messages.concat([ evt.data ]) 
     }) 
    }; 

    // for testing: sending a message to the echo service every 2 seconds, 
    // the service sends it right back 
    setInterval(_ =>{ 
     this.connection.send(Math.random()) 
    }, 2000) 
    }, 
    render: function() { 
    // render the messages from state: 
    return <ul>{ this.state.messages.map((msg, idx) => <li key={'msg-' + idx }>{ msg }</li>)}</ul>; 
    } 
}); 
+0

- ちょっといいですね。でも、JSFiddleの設定が間違っています。元のReact JSFiddle **のエラーをフォークしてください。私の構造は有効ではないと思います。私の反応アプリの構造を作る方法を教えてください?つまり、html、js、webpack.config.js&package.json – kit

+0

このエラーはどこにありますか?私の答えにリンクされているデモのフィドルで? – pawel

+0

はい...私はちょうどjsコードnの変更wsのURLを配置していると私たちはこの

0
Just create rest program from server side and create the connection at Web page 

var connection = new WebSocket('ws://localhost/echo', ['soap', 'xmpp']); 

opening the connection 
connection.onopen = function() { 
    connection.send('Ping'); // 
}; 


connection.onerror = function (error) { 
    console.log('WebSocket Error ' + error); 
}; 

//to receive the message from server 
connection.onmessage = function (e) { 
    console.log('Server: ' + e.data); 
}; 

// Sending String 
connection.send('your message'); 


At server side you will get session and message ,So you can do communication with N sessions 
関連する問題