尝试将文件从 C# 客户端发送到节点.js TCP 服务器
本文关键字:节点 js 服务器 TCP 客户端 文件 | 更新日期: 2023-09-27 17:56:35
我有以下代码:
C# 客户端:
class Program
{
static void Main(string[] args)
{
var client = new TcpClient(AddressFamily.InterNetwork);
client.Connect("127.0.0.1", 9090);
byte[] buffer = Encoding.Default.GetBytes(Program.ReadFile(@"C:'pub'image.jpg"));
using (var stream = client.GetStream())
{
stream.Write(buffer, 0, buffer.Length);
}
Console.WriteLine("File sent.");
Console.ReadLine();
}
public static string ReadFile(string path)
{
string content = string.Empty;
using (var stream = new FileStream(path, FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
}
return content;
}
}
节点.js服务器:
var net = require('net');
var fs = require('fs');
var server = net.createServer(function (socket)
{
var buffer = new Buffer(0, 'binary');
socket.on('data', function (data)
{
buffer = Buffer.concat([buffer, new Buffer(data, 'binary')]);
});
socket.on("end", function (data)
{
fs.writeFile("image.jpg", buffer);
buffer = new Buffer(0, 'binary');
});
});
server.listen(9090, '127.0.0.1');
这行不通。文件到达时总是损坏。我做错了什么?
您的问题在于如何在 C# 中读取文件。如果将文件从 C# 写回磁盘,则可以看到字节数如何不匹配:
// This code does not work
// the number of bytes in image2.jpg won't match image.jpg
byte[] buffer = Encoding.Default.GetBytes(Program.ReadFile(@"C:'pub'image.jpg"));
File.WriteAllBytes(@"c:'pub'image2.jpg", buffer);
将读取更改为改用本机 C# ReadAllBytes:
// This works
// the number of bytes in image2.jpg will match image.jpg
byte[] buffer = File.ReadAllBytes(@"C:'temp'file.jpg");
File.WriteAllBytes(@"c:'pub'image2.jpg", buffer);
您的 Node.js 代码是正确的,并且在您从 C# 向其发送正确的字节后即可工作。
这是
最有可能的编码问题。
我会尝试这样做:
1) C#
:Encoding.UTF8.GetBytes(Program.ReadFile(@"C:'pub'image.jpg")); //EXPLICITLY SPECIFY UTF8 ENCODING
和
2) 在JS
: var buffer = new Buffer(0);
作为,根据节点.js文档:
分配一个包含给定 str 的新缓冲区。 编码默认值为 "UTF8"。
希望这有帮助。