邹老师视频讲的是客户端给服务端发文件,反过来服务端能不能给客户端发文件,试了n次了实现不了,代码也不知道哪里错了- void jieshou()
- {
- byte[] message = new byte[1024 * 1024 * 2];//定义接受数据的缓存数组
- while (true)//是客户端不断接受发送的数据
- {
- int length= socket.Receive(message);//通信套接字接收数据的方法 存在message数组中
- if (message[0] ==0)
- {
- string meg = System.Text.Encoding.UTF8.GetString(message, 0, length);//把接受到得数据转换为string
- textBox3.AppendText(meg + "\n");//输出转换后的信息
- }
- else
- {
- MessageBox.Show("正在接受文件");
- SaveFileDialog baocun = new SaveFileDialog();
- if (baocun.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- string lujin= baocun.FileName;
- using (FileStream xie = new FileStream(lujin, FileMode.Create))
- {
- xie.Write(message ,1,length-1 );
- textBox3.AppendText("文件已保存" + lujin);
- }
- <DIV class=blockcode>
- <BLOCKQUOTE>private void button4_Click(object sender, EventArgs e)
- {
- OpenFileDialog wenjian=new OpenFileDialog ();
- if (wenjian.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- textBox5.Text = wenjian.FileName;
- }
- }
- private void button5_Click(object sender, EventArgs e)
- {
- using (FileStream dkwenjian = new FileStream(textBox5.Text, FileMode.Open)) //参数一为文件的路径,参数二为打开方式
- {
- byte[] mgwenjian=new byte [1024*1024*2];//定义一个数组(缓冲区)
- int length= dkwenjian.Read(mgwenjian ,0,mgwenjian.Length );//(将文件写入数组)注意看参数二为0,就是从0位置开始写入
- byte []sswenjian=new byte [length+1];
- sswenjian[0] = 1;
- //for (int i = 0; i < length; i++)
- //{
- // sswenjian[i + 1] = mgwenjian[i];
- //}
- Buffer.BlockCopy(mgwenjian ,0,sswenjian ,1,length );
- ss[listBox1 .Text ] . Send(sswenjian);
- textBox3.AppendText("文件已发送");
- }
- }
复制代码 }
}
}
}上面是客户端接收文件方法和服务端发送文件方法, |