尝试将文件从 C# 客户端发送到节点.js TCP 服务器
Trying to send a file from a C# client to a node.js TCP server
我有以下代码:
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"。
希望这有帮助。
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 节点.js将变量显示为 HTML
- 如何解决'窗口未定义'终端上的节点JS出错
- S3文件上传文件对象使用节点js
- 在节点 js 中使用护照本地模块验证(登录)密码时出错
- 嵌套的promise节点js
- 使用节点JS发送电子邮件
- 节点JS重定向循环
- 起始节点.js用于并行的线程池
- 获取图像节点js的主色
- 调整节点js中的图像大小
- 节点JS express和控制台输出到命令行与浏览器
- 节点JS:时间机器坏了——timekeeper.travel不做时间旅行
- 如何访问日期并将其插入数据库?节点.JS&MongoDB
- 节点.js快速删除 req.body 不起作用
- 节点.js中的嵌套异步操作
- 如何在核心php应用程序中使用节点js json Web令牌库
- 使用节点js的Bootstrap和Jquery
- 节点.js加密输入/输出类型
- 节点.js在不可能的地方打印“未定义”