LarryDpk
发布于 2024-08-11 / 150 阅读
1

A WebSocket Example Built With Node And ReactJS

#JS

A WebSocket Example Built With Node And ReactJS

Creating a WebSocket project with a Node.js backend and a React.js frontend is a great way to build real-time applications. Below is a step-by-step guide to help you set up these two sub-projects.

Project Structure

Your project structure will look something like this:

websocket-project/
├── server/
│   ├── package.json
│   ├── server.js
├── ui/
│   ├── package.json
│   ├── public/
│   ├── src/
│   │   ├── App.js
│   │   ├── index.js
├── README.md

Step 1: Set Up the Backend (Node.js)

  1. Create the Backend Directory

    mkdir server
    cd server
    
  2. Initialize the Node.js Project

    npm init -y
    
  3. Install Required Dependencies

    npm install ws express
    
  4. Create server.js

    • This file will create an Express server and a WebSocket server using the ws library.
    // backend/server.js
    const express = require('express');
    const http = require('http');
    const WebSocket = require('ws');
    
    const app = express();
    const server = http.createServer(app);
    const wss = new WebSocket.Server({ server });
    
    // Serve static files from the frontend
    app.use(express.static('../ui/build'));
    
    // WebSocket connection
    wss.on('connection', (ws) => {
        console.log('New client connected');
    
        ws.on('message', (message) => {
            console.log(`Received: ${message}`);
            ws.send(`Echo: ${message}`);
        });
    
        ws.on('close', () => {
            console.log('Client disconnected');
        });
    });
    
    // Start the server
    server.listen(8080, () => {
        console.log('Server is running on http://localhost:8080');
    });
    
  5. Run the Backend Server

    node server.js
    

Step 2: Set Up the Frontend (React.js)

  1. Create the Frontend Directory

    npx create-react-app frontend
    cd frontend
    
  2. Modify App.js

    • Connect to the WebSocket server and display the messages.
    // frontend/src/App.js
    import React, { useEffect, useState } from 'react';
    
    function App() {
        const [messages, setMessages] = useState([]);
        const [input, setInput] = useState('');
        const [ws, setWs] = useState(null);
    
        useEffect(() => {
            const socket = new WebSocket('ws://localhost:8080');
    
            socket.onopen = () => {
                console.log('Connected to WebSocket server');
            };
    
            socket.onmessage = (event) => {
                setMessages((prevMessages) => [...prevMessages, event.data]);
            };
    
            socket.onclose = () => {
                console.log('Disconnected from WebSocket server');
            };
    
            setWs(socket);
    
            return () => {
                socket.close();
            };
        }, []);
    
        const sendMessage = () => {
            if (ws && input.trim()) {
                ws.send(input);
                setInput('');
            }
        };
    
        return (
            <div style={{ padding: '20px' }}>
                <h1>WebSocket Chat</h1>
                <div>
                    <input
                        type="text"
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                        style={{ marginRight: '10px' }}
                    />
                    <button onClick={sendMessage}>Send</button>
                </div>
                <div style={{ marginTop: '20px' }}>
                    <h2>Messages:</h2>
                    {messages.map((msg, index) => (
                        <p key={index}>{msg}</p>
                    ))}
                </div>
            </div>
        );
    }
    
    export default App;
    
  3. Run the Frontend

    npm start
    
    • The React app will run at http://localhost:3000 by default.

Step 3: Connect the Frontend and Backend

  • When you start both the backend and frontend, they will connect via WebSocket.
  • Open the frontend in your browser (http://localhost:3000) and open the console to see WebSocket logs.
  • You can type messages in the input box, and they will be sent to the WebSocket server, which will echo them back.

Step 4: Build for Production (Optional)

  1. Build the React App

    cd frontend
    npm run build
    
  2. Serve the Built Files in Express

    • The Express server in the backend will serve the static files from the React build folder.
    • Modify the backend server.js to serve the React app:
    // Serve React build files
    app.use(express.static('../frontend/build'));
    
    // Fallback to index.html for React Router
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, '../frontend', 'build', 'index.html'));
    });
    
  3. Run the Backend Again

    node server.js
    
  • Now, when you visit http://localhost:8080, you’ll see your React app served by the Express server, and WebSocket communication will work as expected.

Code

Please check the code in GitHub.