使用TCP发送时收到的文件为空 [英] the file received as empty while sending using TCP

查看:158
本文介绍了使用TCP发送时收到的文件为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在接收文件时使用C#通过TCP发送文件我发现它是0 KB如何修复它?这是代码//服务器



im trying to send file over TCP using C# while receiving file i found that it's 0 KB how to Fix it ? here's the Code //server

TcpListener list = new TcpListener(localAddr, port);
           list.Start();
           TcpClient client  = list.AcceptTcpClient();//accepting connection with client when send button is clicked there .. !
           StreamReader s = new StreamReader(client.GetStream());
           Stream st = client.GetStream();
           rd = s.ReadLine();
           //FileStream fileStream = new FileStream(textBox1.Text + "\\" + rd.Substring(0, rd.LastIndexOf('.')), FileMode.Create, FileAccess.Write, FileShare.ReadWrite);//new file stream

           FileStream fileStream = new FileStream(folderBrowserDialog1.SelectedPath , FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);//new file stream

           int byteSize = 0;
           byte[] b1 = new byte[2048];



           while ((byteSize = st.Read(b1, 0, b1.Length)) > 0)//if stream read any thing that mean the file didn't finish yet !
           {
             fileStream.Write(b1, 0, byteSize);//write data in file till it finishes


           }

推荐答案

你好。

我真的很长时间一直在努力寻找答案。使用StreamReader可能是一个好主意,但我通过使用异步方法回调和使用AsyncResult进行了传输。然后只发送文件的普通字节。但是,我遇到的下一个问题是检查文件数据何时结束。这可以通过在末尾放置一个字符串关键字bbyte或一些唯一的字节序列来完成。然后你只需剪切它,你就有了文件的字节,后来写入文件。



然而,使用数组的工作非常不舒服,制作互联网应用程序的最佳方法是使用WPF或其他方法来处理这个问题。 TCP非常适合做聊天,或者我用它做局域网卡游戏,因为我必须发送的只是卡的身份证,并更新健康状况。



如果您需要帮助,请将我添加到Skype,用户名:vojtech.dusny,我们可以谈谈它。
Hi there.
I have been troubling with this really really long time, trying to find an answer. Using StreamReader may be a good idea, but I did the transfer by using async method callbacks, and using AsyncResult. Then sending only the plain bytes of the file. However, the next problem I encountered was checking when the file data ends. This can be done by putting a string keyword as bbyte at the end or some unique sequence of bytes. You then just cut it, and you have bytes of the file, wich are later on written to file.

The work with the arrays is quite uncomfortable, however, and the best way to make internet apps is to use WPF or something that is done to handle this. The TCP is quite good to make for example a chat, or I did LAN card game with it, because all I had to send was ID of card, and update the health.

If you need some help, add me at skype, username: vojtech.dusny, we can talk about it.


这篇关于使用TCP发送时收到的文件为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆