Last active
May 19, 2020 12:47
-
-
Save kianaditya/c3ee3b5a28290b990b6c5de3a1207f8b to your computer and use it in GitHub Desktop.
App.js for websocket-testing demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//App.js | |
import React, { useState } from 'react' | |
const App = () => { | |
const [message, setMessage] = useState('websocket is closed') | |
return ( | |
<div className="App"> | |
<p id="websocket">{message}</p> | |
<WebsocketHandler setMessage={setMessage} /> | |
</div> | |
) | |
} | |
export default App | |
// WebsocketHandler does what the name suggests - | |
// launch/close websocket client and receive messages | |
const websocketUrl = 'ws://127.0.0.1:5000' | |
const WebsocketHandler = ({ setMessage }) => { | |
const ws = new WebSocket(websocketUrl) | |
ws.onopen = () => { | |
console.log('conn open') | |
ws.send('connection is open') | |
} | |
ws.onmessage = (message) => { | |
setMessage(message.data) | |
console.log('onmessage triggered', message) | |
ws.send('message received') | |
} | |
ws.onclose = () => { | |
console.log('connection closed') | |
} | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment