📜  react native socket io - Javascript(1)

📅  最后修改于: 2023-12-03 14:46:56.924000             🧑  作者: Mango

React Native Socket.IO - Javascript

React Native Socket.IO is a library that enables real-time, bidirectional and event-based communication between a client and a server. It is built on top of the WebSocket protocol and allows developers to easily integrate real-time functionality in their React Native applications.

Installation

To install the library, simply run the following command:

npm install socket.io-client
Usage

To use Socket.IO in your React Native application, follow these steps:

  1. Import the library:
import io from 'socket.io-client';
  1. Create a Socket.IO connection:
const socket = io('http://localhost:3000');

This will create a connection to the Socket.IO server running on http://localhost:3000.

  1. Listen for events:
socket.on('event', (data) => {
  console.log(data);
});

This will listen for the event event and log the data.

  1. Emit events:
socket.emit('event', data);

This will emit the event event with the data.

Example

Here is an example of a simple React Native chat application using Socket.IO:

import React, { useState, useEffect } from 'react';
import { TextInput, Button, FlatList, StyleSheet, Text, View } from 'react-native';
import io from 'socket.io-client';

const socket = io('http://localhost:3000');

export default function App() {
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    socket.on('message', (data) => {
      setMessages((prevMessages) => [...prevMessages, data]);
    });
  }, []);

  const sendMessage = () => {
    socket.emit('message', message);
    setMessage('');
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={messages}
        renderItem={({ item }) => <Text>{item}</Text>}
        keyExtractor={(item, index) => index.toString()}
      />
      <View style={styles.footer}>
        <TextInput style={styles.input} value={message} onChangeText={setMessage} />
        <Button title="Send" onPress={sendMessage} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  footer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10,
    paddingVertical: 5,
  },
  input: {
    flex: 1,
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginRight: 10,
    paddingHorizontal: 10,
  },
});

This will create a chat application that listens for message events and emits message events when the user sends a message.

Conclusion

React Native Socket.IO is an excellent library for integrating real-time functionality in your React Native applications. With only a few lines of code, you can easily create bidirectional communication between a client and a server.