Created
January 16, 2020 02:24
-
-
Save topherPedersen/4c1d6452689194352a43082af35f777d to your computer and use it in GitHub Desktop.
WebSockets in React Native: Hello, World with the WebSocket.org Echo Endpoint
This file contains 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
// REFERENCE (ws.send) | |
// https://dev.to/finallynero/using-websockets-in-react-4fkp | |
// REFERENCE (official react-native docs) | |
// https://facebook.github.io/react-native/docs/network#websocket-support | |
import React from 'react'; | |
import { | |
SafeAreaView, | |
StyleSheet, | |
ScrollView, | |
View, | |
Text, | |
StatusBar, | |
Button, | |
} from 'react-native'; | |
var ws = new WebSocket('ws://echo.websocket.org/'); | |
ws.onopen = () => { | |
alert("ws.onopen called!"); | |
ws.send('something'); | |
} | |
ws.onmessage = (e) => { | |
alert("ws.onmessage called!"); | |
} | |
ws.onerror = (e) => { | |
alert("ws.onerror called!"); | |
} | |
ws.onclose = (e) => { | |
alert("ws.onclose called!"); | |
} | |
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
} | |
handlePingWebSocketServer() { | |
ws.send("hello, world"); | |
} | |
render() { | |
return( | |
<View> | |
<Text>hello, world</Text> | |
<Button | |
title="Ping WebSocket Server" | |
onPress={ () => this.handlePingWebSocketServer() } /> | |
</View> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment