Last active
July 18, 2024 07:24
-
-
Save Nyaasu66/b68cd8a0f5f8c5a28b551ce682883ce1 to your computer and use it in GitHub Desktop.
RN + websocket 客户端最小实现
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
import React, {useEffect, useRef} from 'react'; | |
import {SafeAreaView, Text, View} from 'react-native'; | |
import {Colors} from 'react-native/Libraries/NewAppScreen'; | |
const url = 'ws://192.168.40.241:8080'; | |
function App(): React.JSX.Element { | |
const ws = useRef<WebSocket>(); | |
const [wsMessage, setWsMessage] = React.useState(''); | |
const connectWebSocket = () => { | |
if (!ws.current) { | |
ws.current = new WebSocket(url); | |
ws.current.onopen = () => { | |
console.log('WebSocket Open:', ws.current); | |
}; | |
ws.current.onerror = error => { | |
console.error('WebSocket Error:', error, error?.message); | |
}; | |
ws.current.onmessage = event => { | |
console.log('WebSocket received a message:', event.data); | |
const message = JSON.parse(event.data); | |
setWsMessage(message.time); | |
}; | |
ws.current.onclose = () => { | |
ws.current = undefined; | |
console.log('WebSocket Closed'); | |
}; | |
} | |
}; | |
useEffect(() => { | |
connectWebSocket(); | |
return () => { | |
if (ws.current) { | |
ws.current.close(); | |
} | |
}; | |
}, []); | |
return ( | |
<SafeAreaView style={{backgroundColor: Colors.lighter}}> | |
<View>{wsMessage && <Text>{wsMessage}</Text>}</View> | |
</SafeAreaView> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment