2017-06-15 56 views
1

我試圖設置一個Websocket客戶端,通過JSON與websever進行通信。我在網上找不到任何好的例子。反應原生Websocket JSON通信

我只找到這段代碼在線:

var ws = new WebSocket('ws://host.com/path'); 

ws.onopen =() => { 
    // connection opened 
    ws.send('something'); // send a message 
}; 

ws.onmessage = (e) => { 
    // a message was received 
    console.log(e.data); 
}; 

ws.onerror = (e) => { 
    // an error occurred 
    console.log(e.message); 
}; 

ws.onclose = (e) => { 
    // connection closed 
    console.log(e.code, e.reason); 
}; 

我不知道如何將這種代碼集成到我的應用程序代碼的功能。 我是否需要爲它安裝一些軟件包? 我正在爲我的研究做一個項目,最後我應該有一個Quiz-App,它連接到服務器以獲取遊戲的問題和答案。

感謝您的幫助!

回答

0

你不需要其他任何東西來處理反應原生WebSocket(或任何相對較新的JS環境for that matter)。你找到的例子幾乎涵蓋了你需要開始的任何事情。下一步是將其綁定到您的React邏輯。例如,您可以創建一個WebSocketController組件,它看起來(詳細內容略)這樣

class WebSocketController extends React.Component { 
    componentDidMount(){ 
    this.ws = new WebSocket('ws://host.com/path'); 
    this.ws.onmessage = this.handleMessage.bind(this); 
    this.ws.onerror = //... 
    } 
    handleMessage(e){ 
    // dispatch event (á la redux, flux), or do something else 
    } 
    componentWillUnmount(){ 
    // close WS 
    } 
} 

你的陣營層級內渲染這一點,它會將您的其餘部件開始。如果你需要更具體的東西,讓我們知道。

+0

我在handleMessage(e)方法中使用console.log(e.data)實現了您的代碼,以查看它是否正常工作,但出現此錯誤:錯誤包裝程序無法偵聽端口8081 最有可能是另一個進程已在使用此端口 運行下面的命令找出哪個進程: lsof的-i:8081 然後,您可以關閉其他程序: 殺-9 或在不同的運行打包港口。 – Hang

+0

這是一個不同的錯誤,通常通過檢查lsof的輸出來修復。可能你有另一個運行在那裏的打包程序實例。 – martinarroyo

+0

好吧,這個錯誤不再存在,但是當我嘗試用console.log(e.data)實現的代碼運行我的應用程序時,它不會在控制檯上顯示任何內容。在我的IDE Webstorm控制檯中,它與此消息交替[intellij]建立與代理(包裝程序)到React Native應用程序 到此消息的連接 [intellij]從代理(包裝程序)斷開連接到React Native應用程序。儘快重新嘗試重新連接... – Hang