如何使用networkstream发送文件? [英] how to sending a file using networkstream ?

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

问题描述

您好,我正在使用tcpListener发送文件,直到发送3MB文件为止一切都很好,这基本上就是我使用的代码

Hello, i''m sending a file using tcpListener, It was all going great until i sent a 3MB file, this is basically the code i use

public frmPrincipal()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;           
        }
        private void btnEnviar_Click(object sender, EventArgs e)
        {
            TcpClient clienteTCP = new TcpClient(AddressFamily.InterNetwork);
            IPAddress[] listaHost = Dns.GetHostAddresses("xxx.xxx.xxx.xxx");//my IPadress
            clienteTCP.BeginConnect(listaHost, 3000, new AsyncCallback(IniciarConexion), clienteTCP);    
        }        
        public void IniciarConexion(IAsyncResult piasResultado)
        {
            TcpClient cliente = piasResultado.AsyncState as TcpClient;
            using (NetworkStream clienteStream = cliente.GetStream())
            {
                ASCIIEncoding encoder = new ASCIIEncoding();
                string arch = "song.mp3";
                byte[] nombre = encoder.GetBytes(arch);
                byte[] ArregloDeArchivo = File.ReadAllBytes(@"C:\Users\Hector\Desktop\" + arch);

                    clienteStream.Write(jeje, 0, jeje.Length);
                    clienteStream.Flush();
...



当我写它发送文件.但是,当收到文件时,文件大小为8KB,为什么会发生这种情况? =(



When i write it sends the file. But, when it is received, the size of the file is 8KB, why this happens ??? =(

推荐答案

您正在将二进制文件视为文本文件.您正在使用ASCII编码,这将更改您正在读取和发送的数据.您必须使用BinaryStream类读取这些文件并获取字节.

如何读取二进制文件 [
You''re treating a binary file as a text file. Youre using the ASCII encoding which will alter the data you''re reading and sending. You have to use the BinaryStream class to read those files and get the bytes.

How to read a binary file[^]


我可以看到您正在一次读取所有文件.但是您是否创建了数组jeje?
在调用clienteStream.Write之前,如何将nombre ArregloDeArchivo 组合到jeje?

在接收方代码上,您必须调用NetworkStream.Read,直到收到所有数据为止.数据不在一个TCP数据包中发送.一个3MB的文件以块的形式发送,您必须读取接收方代码中的所有块.

关于接收方.查看
TCP/IP协议设计:消息框架 [ ^ ]
I can see that you are reading all the file in at once. But were do you create the array jeje ?
How do you combine nombre and ArregloDeArchivo to jeje before you call clienteStream.Write ?

On the receive side code, you have to call NetworkStream.Read until you have received all data. Data it not send in one TCP packet. A 3MB file is send in chunks, and you have to read all chunks in the receive side code.

Regards receiving side. Check out TCP/IP Protocol Design: Message Framing[^]


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

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