如何将多个数据流从单个客户端发送到 TCP 服务器



服务器端代码

var net = require('net');
var server = net.createServer((connection) => {
console.log('server connected');
connection.on('data', (data) => {
console.log('data received');
console.log('data is: n' + data);
});
});
var HOST = '127.0.0.1';
var PORT = '8000'

server.listen(PORT, HOST, function() {
//listening
console.log('server is listening to ' + PORT + 'n');
server.on('connection', function(){
console.log('connection made...n')
})
});

客户端代码

var client = new net.Socket()
//connect to the server
client.connect(PORT,HOST,function() {
'Client Connected to server'
//send a file to the server
var fileStream = fs.createReadStream(__dirname + '/readMe.txt');
// console.log(__dirname + '/readMe.txt');
fileStream.on('error', function(err){
console.log(err);
})
fileStream.on('open',function() {
fileStream.pipe(client);
});
});
//handle closed
client.on('close', function() {
console.log('server closed connection')
});
client.on('error', function(err) {
console.log(err);
});

我想知道如何实现创建客户端和TCP服务器,并将多个数据从一个客户端发送到服务器。

我知道可以有多个客户端可以连接到服务器,该服务器请求服务器并获得响应,但我不想这样,我想知道单个客户端是否有可能将多个数据流发送到node.js中的服务器。

问题是假设有一个文件,其中存在 200 行块数据,所以我知道我们可以使用createReadStream读取该文件,但假设有多个文件有 200 行数据(示例(,那么如何通过 TCP 服务器发送这些多个文件

任何例子都会被理解。

请用一个例子给出解释,因为我是节点的新手.js

上面的例子是将一个文件的数据发送到服务器,我的问题如果客户端想发送数百个文件(或任何数据流(怎么办,那么他如何通过单个介质发送到TCP服务器呢?

这可以使用net模块、fs模块和用于循环文件的基本forEach构造来实现:

服务器.js

const net = require('net');
const host = "localhost";
const port = 3000;
const server = net.createServer((connection) => {
console.log('server connected');
connection.on('data', (data) => {
console.log(`data received: ${data}`);
});
});
server.listen(port, host, function () {
console.log(`server is listening on ' + ${port}`);
server.on('connection', function () {
console.log('connection made...n')
})
});

客户端.js

const net = require("net");
const fs = require("fs");
const port = 3000;
const host = "localhost";
const files = [
"file1.txt",
"file1.txt",
"file1.txt"
// As many files as you want
]
const client = new net.Socket()
client.connect(port, host, function () {
files.forEach(file => {
const fileStream = fs.createReadStream(file);
fileStream.on('error', function (err) {
console.log(err);
})
fileStream.on('open', function () {
fileStream.pipe(client);
});
});
});
client.on('close', function () {
console.log('server closed connection')
});
client.on('error', function (err) {
console.log(err);
});

相关内容

最新更新