您的位置:首页 > 编程语言 > C#

【求助】C# Socket 编程 求救 为什么此程序 文件传输时会有大小限制?

2009-12-25 13:54 309 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace File
{
public partial class FileTrans : Form
{
public FileTrans()
{
InitializeComponent();
}
private void SelectBtn_Click(object sender, EventArgs e)
{
Ofd.ShowDialog();
SelectBox.Text = Ofd.FileName;
}
private void SendBtn_Click(object sender, EventArgs e)
{
//tcp.Start();
String path = SelectBox.Text;
TcpClient client = new TcpClient();
try
{
client.Connect(IPAddress.Parse(IPBox.Text), 5000);
MsgBox.AppendText("连接成功!");
}
catch (Exception E)
{
MsgBox.AppendText(E.Message);
}

FileStream file = new FileStream(path,FileMode.Open,FileAccess.Read);
NetworkStream stream = client.GetStream();
byte[] by = new byte [2048];
int data;
while ((data = file.Read(by, 0, 2048)) != 0)
{
stream.Write(by,0,by.Length);//发送文件到目标机器
stream.Flush();
by = new byte[2048];
}
client.Client.Shutdown(SocketShutdown.Both);
stream.Close();
file.Close();
MsgBox.AppendText("/n发送文件" + Ofd.FileName);
}
private void Receive_Click(object sender, EventArgs e)
{

Sfd.ShowDialog();
String path = Sfd.FileName;
TcpClient client = tcp.AcceptTcpClient();

FileStream fs = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write);
NetworkStream stream = client.GetStream();
int count;
byte[] by = new byte[2048];
while ((count = stream.Read(by,0,by.Length)) != 0)
{
fs.Write(by, 0, count);
stream.Flush();
by = new byte[2048];
}
stream.Close();
fs.Close();
//sock.Close();
MsgBox.AppendText("/n接受成功");
}
TcpListener tcp = null;

private void FileTrans_Load(object sender, EventArgs e)
{
tcp = new TcpListener(5000);
tcp.Start();

}
}
}


为什么此段代码 会有文件大小限制 ?

while ((data = file.Read(by, 0, 2048)) != 0)
{
stream.Write(by,0,by.Length);//发送文件到目标机器
stream.Flush();
by = new byte[2048];
}


不是应该循环读文件流么? 求大侠指教。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: