门户网站php源码,外国人学做中国菜 网站,wordpress破解登录,如何制作自己的视频网站1.4 使用 WebSocket 实现实时通信
除了 fetch 和 axios 这样的 HTTP 请求方式#xff0c;React Native 还支持 WebSocket#xff0c;用于实现客户端与服务器之间的实时双向通信。WebSocket 适用于需要实时数据推送的场景#xff0c;如聊天应用、实时通知、实时数据更新等。…1.4 使用 WebSocket 实现实时通信
除了 fetch 和 axios 这样的 HTTP 请求方式React Native 还支持 WebSocket用于实现客户端与服务器之间的实时双向通信。WebSocket 适用于需要实时数据推送的场景如聊天应用、实时通知、实时数据更新等。
1.4.1 WebSocket 简介
WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议。与传统的 HTTP 请求不同WebSocket 连接一旦建立就可以保持打开状态服务器可以主动向客户端推送数据而无需客户端不断轮询。
WebSocket 的特点
全双工通信 客户端和服务器可以同时发送和接收数据。实时性 数据可以实时推送无需客户端轮询。轻量级 WebSocket 协议开销小适合实时通信。
1.4.2 在 React Native 中使用 WebSocket
React Native 提供了 WebSocket API用于创建和管理 WebSocket 连接。
基本用法
import React, { useEffect, useState } from react;
import { View, Text, StyleSheet } from react-native;const WebSocketExample () {const [socket, setSocket] useState(null);const [message, setMessage] useState();const [messages, setMessages] useState([]);useEffect(() {// 创建 WebSocket 连接const ws new WebSocket(wss://echo.websocket.org);// 连接打开ws.onopen () {console.log(WebSocket connection established);ws.send(Hello Server!);};// 接收到消息ws.onmessage (e) {console.log(Message received:, e.data);setMessages((prevMessages) [...prevMessages, e.data]);};// 连接关闭ws.onclose (e) {console.log(WebSocket connection closed:, e.reason);};// 连接错误ws.onerror (e) {console.error(WebSocket error:, e.message);};setSocket(ws);// 清理资源return () {if (ws.readyState WebSocket.OPEN) {ws.close();}};}, []);const sendMessage () {if (socket) {socket.send(message);setMessage();}};return (View style{styles.container}Text style{styles.title}WebSocket Example/TextView style{styles.inputContainer}TextInputstyle{styles.input}value{message}onChangeText{setMessage}placeholderType a message/Button titleSend onPress{sendMessage} //ViewView style{styles.messagesContainer}{messages.map((msg, index) (Text key{index} style{styles.message}{msg}/Text))}/View/View);
};const styles StyleSheet.create({container: {flex: 1,padding: 20,backgroundColor: #fff,},title: {fontSize: 20,fontWeight: bold,marginBottom: 10,},inputContainer: {flexDirection: row,alignItems: center,marginBottom: 10,},input: {flex: 1,height: 40,borderColor: #ccc,borderWidth: 1,paddingHorizontal: 10,marginRight: 10,},messagesContainer: {flex: 1,borderTopWidth: 1,borderColor: #ccc,paddingTop: 10,},message: {fontSize: 16,marginBottom: 5,},
});export default WebSocketExample;解释 创建 WebSocket 连接 使用 new WebSocket(wss://echo.websocket.org) 创建一个 WebSocket 连接。wss 表示安全的 WebSocket 连接使用 TLS 加密。 连接事件 onopen连接打开时触发可以发送初始消息。onmessage接收到消息时触发更新状态。onclose连接关闭时触发。onerror连接出错时触发。 发送消息 调用 socket.send(message) 发送消息到服务器。 清理资源 在组件卸载时检查 WebSocket 连接是否打开如果打开则关闭连接。
作者简介
前腾讯电子签的前端负责人现 whentimes tech CTO专注于前端技术的大咖一枚一路走来从小屏到大屏从 Web 到移动什么前端难题都见过。热衷于用技术打磨产品带领团队把复杂的事情做到极简体验做到极致。喜欢探索新技术也爱分享一些实战经验帮助大家少走弯路
温馨提示可搜老码小张公号联系导师