【问题标题】:Trying to send a file from a C# client to a node.js TCP server尝试将文件从 C# 客户端发送到 node.js TCP 服务器
【发布时间】:2014-05-15 03:44:33
【问题描述】:

我有以下代码:

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;
    }
}

node.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# javascript node.js networking tcp


【解决方案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# 发送正确的字节就可以工作。

【讨论】:

    【解决方案2】:

    这很可能是编码问题。

    我会尝试做:

    1) 在C#: Encoding.UTF8.GetBytes(Program.ReadFile(@"C:\pub\image.jpg")); //EXPLICITLY SPECIFY UTF8 ENCODING

    2) 在JS: var buffer = new Buffer(0);

    如,根据node.js documentation

    分配一个包含给定 str 的新缓冲区。编码默认为 'utf8'。

    希望这会有所帮助。

    【讨论】:

    • 感谢您的回答。使编码符合要求确实有意义,但不幸的是图像仍然损坏。
    • @prc322: 你在 C# 中发送的字节数是否等于你在 node.js 中收到的字节数?
    • @prc322:另外,查看文档我没有看到带有第二个参数的 concat 方法,您在其中传递“二进制”。只需将其删除,保留如下: Buffer.concat([buffer, new Buffer(data)]);看看这是否有帮助。
    • 将行改为 Buffer.concat([buffer, new Buffer(data)]);没有“帮助”,图像仍然损坏。另外,原始镜像的大小是48KB,我写到服务器端磁盘的镜像大小是82.9KB。在尝试征服这样的事情之前,我应该阅读哪些主题?
    • @prc322:你有没有尝试使用base64字符串表示图像?
    猜你喜欢
    • 2019-03-12
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2015-05-02
    • 2020-11-06
    • 2023-04-03
    • 2013-05-23
    相关资源
    最近更新 更多