我正在研究一个项目,我坚持转移文件...到目前为止它的工作,但在我看来,这不是正确的方法。当我发送文件时,我发送后等待1秒钟。之后,我将停止命令发送到接收器,以便他(接收器)可以关闭文件。每个字节数组发送到字符串,以便我可以检查接收的字节数组是否是停止命令。如果没有sleep命令,stop命令将不会被分开发送(它将与另一个字节数组一起发送)。有没有办法在不关闭套接字的情况下停止文件传输效率更高? 发送功能:
public void sendFile()
{
string filename = Path.GetFileName(fileLocation);
byte[] SendingBuffer = null;
server = client.GetStream();
int BufferSize = 1024;
try
{
using (FileStream fs = File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.None))
{
int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(fs.Length) / Convert.ToDouble(BufferSize)));
int TotalLenght = (int)fs.Length, CurrentPacketLengh = 0;
mainWindowClass.progressBar2.Dispatcher.Invoke(new Action(()=> mainWindowClass.progressBar2.Maximum = NoOfPackets));
sendCommand("sndfil"+ filename, "c0mm@nds t0 s3nd %!3");
for (int i = 0; i < NoOfPackets; i++)
{
//MessageBox.Show(NoOfPackets.ToString() + " " + i);
if (TotalLenght > BufferSize)
{
CurrentPacketLengh = BufferSize;
TotalLenght = TotalLenght - CurrentPacketLengh;
}
else
CurrentPacketLengh = TotalLenght;
SendingBuffer = new byte[CurrentPacketLengh];
fs.Read(SendingBuffer, 0, CurrentPacketLengh);
server.Write(SendingBuffer, 0, (int)SendingBuffer.Length);
mainWindowClass.progressBar2.Dispatcher.Invoke(new Action(() => mainWindowClass.progressBar2.Value++));
}
Thread.Sleep(1000);
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("stopfile");
server.Write(outStream, 0, (int)outStream.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
mainWindowClass.progressBar2.Dispatcher.Invoke(new Action(() => mainWindowClass.progressBar2.Value=0));
}
接收功能:
public void receiveFile(string name)
{
string fileName = (System.IO.Path.Combine(mainWindowClass.saveFolder, name));
byte[] RecData = new byte[1024];
int RecBytes;
NetworkStream netstream = null;
try
{
int total = 0;
netstream = client.GetStream();
FileStream Fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
RecBytes = netstream.Read(RecData, 0, RecData.Length);
char[] chars = new char[RecBytes];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(RecData, 0, RecBytes, chars, 0);
System.String recv = new System.String(chars);
while (recv!="stopfile")
{
total += RecData.Length;
Fs.Write(RecData, 0, RecBytes);
RecBytes = netstream.Read(RecData, 0, RecData.Length);
chars = new char[RecBytes];
d = System.Text.Encoding.UTF8.GetDecoder();
charLen = d.GetChars(RecData, 0, RecBytes, chars, 0);
recv = new System.String(chars);
}
Fs.Close();
mainWindowClass.testLabel.Dispatcher.Invoke(new Action(() => mainWindowClass.testLabel.Content += total.ToString()));
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
我在Google上搜索了解决方案,但我发现只是关闭了客户端/服务器。