Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created January 16, 2020 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/4c1d6452689194352a43082af35f777d to your computer and use it in GitHub Desktop.
Save topherPedersen/4c1d6452689194352a43082af35f777d to your computer and use it in GitHub Desktop.
WebSockets in React Native: Hello, World with the WebSocket.org Echo Endpoint
// 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