使用TCP时文件大小更改

时间:2018-12-06 05:30:51

标签: c# file tcp transfer

我通过tcp将4 MB的文件发送到本地服务器。但是该文件在本地服务器上存储为36 MB。

出什么问题了?

我将文件转换为字符串(base64),然后添加到json中。然后将json转换为byte []并发送。

客户端将字节发送到服务器:

await nwStream.WriteAsync(json, 0, json.Length);

NetworkStream streams = client.GetStream();
int Q = 0;
int M = json.Length;
int ss = 150001;

bool go = true;
while (go)
{
    if(M< ss)
    {
        go = false;
        ss = M;
    }
    if (M < 0)
    {
        go = false;
        ss = M + ss;
    }
    await streams.WriteAsync(json, Q,ss);
    Q += ss;
    M -= ss;
}

和服务器端获取字节[]:

Byte[] bytes = new Byte[150001];
int i;
try
{
    // Loop to receive all the data sent by the client.
    while ((i = await stream.ReadAsync(bytes, 0, bytes.Length)) != 0)
    {
        // bytes contains received data in byte[].
        // Translate data bytes to a UTF-8 string.
        byte[] receivedBuffer = new byte[i];
        Array.Copy(bytes, receivedBuffer, i);
        data += System.Text.Encoding.UTF8.GetString(receivedBuffer);
        if (data.IndexOf("}") > 0)
        {
            break;
        }
    }


}
catch (Exception ex)
{

}

编辑:

然后保存文件,我将“数据”编码为UTF8字符串,然后转换为DeserializeObject。

             var pi = Convert.FromBase64String(picbas64);
        var x = (Bitmap)((new ImageConverter()).ConvertFrom(pi));
        string path = @"pic\Operation\" + name + ".jpg";
        var ZZ = x;
        ZZ.Save(path);
        return path;

0 个答案:

没有答案