2016-06-30 53 views
6

我想創建一個基於Websocket的客戶端 - 服務器應用程序。在這我創建節點js websocket服務器正在等待客戶端。現在我想創建反應js websocket客戶端。我正在使用react js作爲websocket,因爲我必須連續呈現哪些服務器作爲簡單的文本消息發送的元素。js如何作爲websocket客戶端?

我很感興趣的實施反應js作爲websocket客戶端。那應該怎麼工作的WebSocket的客戶端,以及如何將發送請求到服務器的WebSocket就像這樣:

'ws://localhost:1234' 

我想知道更多關於WebSocket的客戶,也想解決這個問題?

+0

我建議你詢問任何其他問題之前,先閱讀https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications。 –

+0

好的...閱讀本頁...但我想在反應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

所以沒有太多的開銷,一個非常簡單的例子就需要兩兩件事:

  1. 與參考的一個組成部分WebSocket連接

  2. 連接上的事件監聽器更新組件的狀態 當消息到達

演示: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代碼修改爲ws url,而在html中我們使用這個

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