如何使用 TCP 从客户端接收一些文件并将这些文件发送到客户端?

问题描述 投票:0回答:1

我想通过TCP协议实时从客户端接收一些文件并将这些文件发送到客户端。这是我的聊天应用程序所必需的。

如何使用 Node.js 中的

net
模块来实现这一目标?请帮我。问候...

javascript node.js sockets tcp backend
1个回答
0
投票

那么您想与 .net 和 Node.js 进行服务器-客户端通信吗?

类似这样的:

服务器代码:

import net from 'net';
import fs from 'fs';

const PORT = 3000; // Port number for TCP server

const server = net.createServer((socket) => {
    console.log('Client connected:', socket.remoteAddress);

    // Handle incoming data from clients
    socket.on('data', (data) => {
        const message = data.toString();
        console.log('Received message:', message);

        // Assuming messages will contain file paths or specific commands for file transfer
        if (message.startsWith('FILE:')) {
            const filePath = message.substring(5); // Extract file path from message
            sendFile(socket, filePath);
        }
    });

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

    // Function to send file to client
    function sendFile(socket, filePath) {
        fs.readFile(filePath, (err, data) => {
            if (err) {
                console.error('Error reading file:', err);
                socket.write(`ERROR: ${err.message}`);
            } else {
                // Send file data to client
                socket.write(data);
                console.log(`Sent file ${filePath} to ${socket.remoteAddress}`);
            }
        });
    }
});

server.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

和客户端代码:

import net from 'net';
import fs from 'fs';

const FILE_PATH = '/path/to/your/file.txt'; // Path to file you want to send

const client = new net.Socket();

client.connect(PORT, 'localhost', () => {
    console.log('Connected to server');
    
    // Send file path to server
    client.write(`FILE:${FILE_PATH}`);

    // Handle incoming data from server (file data)
    client.on('data', (data) => {
        // Assuming data received is file content
        console.log('Received data from server:', data);

        // Save received file data to a file
        fs.writeFile('received-file.txt', data, (err) => {
            if (err) {
                console.error('Error saving file:', err);
            } else {
                console.log('File saved successfully');
            }
        });

        // Close connection after receiving file
        client.end();
    });

    // Handle server connection close
    client.on('close', () => {
        console.log('Connection closed');
    });
});

© www.soinside.com 2019 - 2024. All rights reserved.