我做了一个简单的服务器和客户端程序,其中服务器从文件中读取数据并通过TCP套接字发送到客户端,但是我获取的数据是对象中的对象,而不是简单的字符串?
所以为什么我看不到data.txt
文件中的纯文本数据。
通过示例进行说明。
这是我的代码:-
服务器代码
const fs = require('fs');
const net = require('net');
const readableData = fs.createReadStream('data.txt', 'utf8');
const server = net.createServer(socket => {
socket.on('data', chunk => {
console.log(chunk.toString());
socket.write(JSON.stringify(readableData));
});
socket.on('end', () => {
console.log("done");
})
socket.on('close', () => {
console.log("closed")
})
});
server.listen(3000);
客户代码
const fs = require('fs');
const net = require('net');
const client = new net.Socket();
client.connect('3000', () => {
console.log("connected");
client.write("Server please send the data");
});
client.on('data', chunk => {
console.log("Data recieved:" + chunk.toString());
});
client.on('finish', () => {
console.log("Work completed");
})
client.on('close', () => {
console.log("connection closed");
})
这是我的具有简单数据的data.txt文件
你好客户,你好吗?
我得到的输出在这里:-
Data recieved:{"_readableState":{"objectMode":false,"highWaterMark":65536,"buffer":{"head":{"data":"Hello client how are you ?","next":null},"tail":{"data":"Hello client how are you ?","next":null},"length":1},"length":26,"pipes":null,"pipesCount":0,"flowing":null,"ended":true,"endEmitted":false,"reading":false,"sync":false,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"paused":true,"emitClose":false,"autoDestroy":false,"destroyed":false,"defaultEncoding":"utf8","awaitDrain":0,"readingMore":false,"decoder":{"encoding":"utf8"},"encoding":"utf8"},"readable":true,"_events":{},"_eventsCount":1,"path":"data.txt","fd":35,"flags":"r","mode":438,"end":null,"autoClose":true,"bytesRead":26,"closed":false}
为什么我不能像在data.txt文件中那样在客户端将数据显示为纯文本的问题。
您的变量readableData
包含一个node.js流对象。那就是那个变量。它仅在当前的node.js实例中使用,因此尝试将该流对象发送到客户端并没有任何用处。
如果要从该'data.txt'
文件中获取所有数据,则有多种选择。
您可以使用fs.readFile()
将整个文件读入本地变量,然后使用socket.write()
发送所有数据。
您可以为每个新的传入请求创建一个附加到文件的新流,然后当数据进入readStream时,可以将其发送到套接字(这通常称为将一个流传送到另一个流中)。如果您使用更高级别的服务器构造(例如http服务器),它们将使管道管理变得非常容易。