【发布时间】:2012-01-28 01:02:52
【问题描述】:
public static void sendFile(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
string fileName = Path.GetFileName(filePath);
byte[] fileData;
try
{
//sending file name and file size to the server
busy = true;
fileSize = fs.Length;
byte[] fileDetial = null;
string detail = fileName + "," + fileSize.ToString();
fileDetial = Encoding.ASCII.GetBytes(detail);
client.Send(fileDetial);
//sending file data to the server
fileData = new byte[packetSize];
count = 0;
sum = 0;
Program.thFP.Start(); // running transfer rate
Program.fp.StatusLabel("Sending data...");
transferRate.timeLeft();
while (sum < fileSize)
{
fs.Seek(sum, SeekOrigin.Begin);
fs.Read(fileData, 0, fileData.Length);
count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
sum += count;
Program.fp.ProgressBarFileHandler(sum, fileSize);
}
}
finally
{
busy = false;
fs.Close();
fileData = null;
MessageBox.Show(string.Format("{0} sent successfully", fileName));
}
}
我猜下面的代码完全没有问题..我认为问题出在 SENDFILE 方法中..但这里是 receiveFile 代码..它可能会有所帮助
public static void ReceiveFile()
{
//receving file name and file size from server
busy = true;
byte[] commandData = new byte[1024];
client.Receive(commandData);
Console.WriteLine(Encoding.ASCII.GetString(commandData));
string[] Command = Encoding.ASCII.GetString(commandData).Split(',');
string fileName = Command[0];
fileSize = Convert.ToInt64(Command[1]);
Program.thFP.Start(); // running transfer rate
Program.fp.StatusLabel("Receiving data...");
transferRate.timeLeft();
// receiving the file data from server
FileStream fs = new FileStream(@"D:\" + fileName, FileMode.Create, FileAccess.Write);
byte[] fileData = new byte[packetSize];
try
{
count = 0;
sum = 0;
while (sum < fileSize)
{
count = client.Receive(fileData,0,fileData.Length, SocketFlags.None);
fs.Seek(sum, SeekOrigin.Begin);
fs.Write(fileData, 0, fileData.Length);
sum += count;
Program.fp.ProgressBarFileHandler(sum,fileSize);
}
}
finally
{
busy = false;
fs.Close();
fileData = null;
MessageBox.Show(string.Format("{0} recevied successfully", fileName));
}
}
【问题讨论】:
-
如果您删除 try...finally 或至少添加一条 catch 语句以查看是否在某处抛出了异常,这可能会有所帮助。
-
我删除了尝试,最后..应用程序没有停止或给我一个错误..我认为第一次传输后套接字出现问题:S
-
您可以运行
netstat来查看端口处于什么状态。 -
从命令提示符运行它:
netstat /?用于选项。 -
@ChrisO 服务器始终处于活动状态......并且工作正常......在我完全发送文件后......我可以关闭客户端并重新打开它并再次重新连接到服务器而无需重新启动服务器应用程序我可以用这种方式发送另一个文件..
标签: c# .net sockets tcp file-transfer