DEV Community

Akram Khan
Akram Khan

Posted on

Use socket.io in react native with nodejs server

Certainly! React Native can be integrated with Socket.io to enable real-time communication in mobile applications. Here's a basic guide on setting up Socket.io with React Native:

Install Required Packages:
Install the necessary packages using npm or yarn. You'll need socket.io-client for the client-side and socket.io for the server-side.

bash
Copy code
npm install socket.io-client
For the server-side (if you have a backend), you'll also need:

bash
Copy code
npm install socket.io
Set Up Socket.io Client in React Native:
Import and set up the Socket.io client in your React Native component.

javascript
Copy code
import React, { useEffect } from 'react';
import io from 'socket.io-client';

const YourComponent = () => {
useEffect(() => {
const socket = io('http://your-server-address'); // Replace with your server address

socket.on('connect', () => {
  console.log('Connected to server');
});

// Handle other events as needed

return () => {
  socket.disconnect();
};
Enter fullscreen mode Exit fullscreen mode

}, []);

return (
// Your component JSX
);
};

export default YourComponent;
Server-Side (Optional):
If you have a server, set up Socket.io on the server. Here's a simple example using Express:

javascript
Copy code
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

io.on('connection', (socket) => {
console.log('Client connected');

// Handle events from clients

socket.on('disconnect', () => {
console.log('Client disconnected');
});
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(Server running on port ${PORT});
});
Usage:
You can now emit and listen for events between the React Native client and the server.

javascript
Copy code
// Emit an event from the client
socket.emit('chat message', 'Hello, server!');

// Listen for events on the client
socket.on('chat message', (msg) => {
console.log(Received message: ${msg});
});
Make sure to replace 'http://your-server-address' with the actual address of your server. This is a basic setup, and you can customize it based on your application's needs.

Top comments (0)