Socket.Receive() 返回不正确的数据量
本文关键字:数据 不正确 返回 Receive Socket | 更新日期: 2023-09-27 18:36:41
作为学校项目,我正在创建一个文件共享应用程序。我将我想要的所有消息发送到服务器,一切都很好,但是当涉及到将文件上传到服务器时,文件永远不会是它应该的样子。我调试了应用程序,发现套接字没有返回正确的字节数。我不知道这是否是正确的方式,但我认为这是错误的。例如,当我上传一个小.txt文件并使用Notepad++打开它时,我在文件末尾看到很多null,这意味着我正在编写更多,而不是应该写入。我在互联网上搜索了它,并在 codeplex 上找到了一个应用程序,它与我正在做的相同,但套接字返回正确的数据量,http://srf.codeplex.com/。
如果有人能帮助我,我将不胜感激。对不起,如果英语很糟糕,它不是我的母语。
处理第一条消息并接收 clint 连接的服务器函数:
public void Brodcast()
{
tcpListener.Start();
while (true)
{
try
{
ClientSocket = tcpListener.AcceptSocket();
MessageReceiving();
}
catch { }
}
}
public void MessageReceiving()
{
if (ClientSocket.Connected)
{
OpenPackage.MessageTypeToBytes RSMessage = new OpenPackage.MessageTypeToBytes();
ClientSocket.Receive(RSMessage.MessageBytes, 512, SocketFlags.None);
if (RSMessage.TypeOfMessage == MessageType.Login)
DoLogin();
else if (RSMessage.TypeOfMessage == MessageType.Download)
SendFile();
else if (RSMessage.TypeOfMessage == MessageType.Upload)
ReceiveFile();
else if (RSMessage.TypeOfMessage == MessageType.NConta)
NewAccount();
else if (RSMessage.TypeOfMessage == MessageType.Search)
SearchResult();
else if (RSMessage.TypeOfMessage == MessageType.Apagar)
DeleteFile();
}
}
服务器:
public void ReceiveFile()
{
try
{
byte[] MessageBytes = new byte[512];
ClientSocket.Receive(MessageBytes, 512, SocketFlags.None);
string Nickname = Encoding.ASCII.GetString(MessageBytes);
string[] CNickFich = Nickname.Split('$');
FileHandler Handler = new FileHandler();
long DirectorySize = Handler.GetDirectorySize("C:''" + CNickFich[0]);
long FileSize = long.Parse(CNickFich[2]);
bool Subs = false;
if ((FileSize + DirectorySize) < MaxFolderSize && MaxFileSize > FileSize)
{
if (!Directory.Exists("C:''" + CNickFich[0]))
Directory.CreateDirectory("C:''" + CNickFich[0]);
if (File.Exists("C:''" + CNickFich[0] + "''" + CNickFich[1]))
{
File.Delete("C:''" + CNickFich[0] + "''" + CNickFich[1]);
Subs = true;
}
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.OK };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
int qtdReceived = 0;
long CurrentSize = 0;
byte[] FileBuffer = new byte[BufferSize];
FileStream FileStr = new FileStream("C:''" + CNickFich[0] + "''" + CNickFich[1], FileMode.CreateNew, FileAccess.Write);
BufferedStream BufferStr = new BufferedStream(FileStr);
while (CurrentSize < FileSize)
{
qtdReceived = ClientSocket.Receive(FileBuffer, 0, FileBuffer.Length, 0);
CurrentSize += qtdReceived;
BufferStr.Write(FileBuffer, 0, qtdReceived);
BufferStr.Flush();
}
BufferStr.Close();
FileStr.Close();
SqlDataAdapter data = new SqlDataAdapter("SELECT COD_CONTA FROM CONTAS WHERE NICKNAME='"
+ CNickFich[0] + "'", OConn);
DataTable dt = new DataTable();
data.Fill(dt);
if (NFicheiro(Handler.MD5HashFromFile("C:''" + CNickFich[0] + "''" + CNickFich[1]), "C:''" + CNickFich[0] + "''" + CNickFich[1], Subs,
int.Parse(dt.Rows[0][0].ToString()), CNickFich[3]))
MessageInBytes.TypeOfMessage = MessageType.OK;
else
MessageInBytes.TypeOfMessage = MessageType.Erro;
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
//NFicheiro(new FileHandler().MD5HashFromFile("C:''" + CNickFich[0] + "''" + CNickFich[1]), "C:''" + CNickFich[0], false, 1, );
}
else
{
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
}
}
catch
{
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
}
}
客户:
private void UploadWork_DoWork(object sender, DoWorkEventArgs e)
{
FileStream FileStr = null;
BufferedStream BufferStr = null;
Stopwatch Counter = new Stopwatch();
try
{
int CurrentProgress = 0;
Program.CTasks.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Program.CTasks.ClientSocket.ReceiveTimeout = 60000;
Program.CTasks.ClientSocket.SendTimeout = 60000;
Program.CTasks.ClientSocket.Connect(IPAddress.Parse(Program.CTasks.HostName), Program.CTasks.Port);
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Upload };
Program.CTasks.ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
FileInfo FileNFO = new FileInfo(Open.FileName);
byte[] NickPath = new byte[512];
byte[] UNickPath = Encoding.ASCII.GetBytes(Program.Nickname + "$" + Open.FileName.Substring(Open.FileName.LastIndexOf('''') + 1) + "$" + FileNFO.Length.ToString() + "$");
byte[] TagCollectionBytes = Encoding.ASCII.GetBytes(TagCollection + "$");
UNickPath.CopyTo(NickPath, 0);
TagCollectionBytes.CopyTo(NickPath, UNickPath.Length);
Program.CTasks.ClientSocket.Send(NickPath, 512, SocketFlags.None);
Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
if (MessageInBytes.TypeOfMessage == MessageType.OK)
{
long FileSize = FileNFO.Length;
long CurrentFileSize = 0;
long qtdRead = 0;
byte[] FileBytes = new byte[BufferSizer];
FileStr = new FileStream(Open.FileName, FileMode.Open, FileAccess.Read);
BufferStr = new BufferedStream(FileStr);
Counter.Start();
while ((qtdRead = BufferStr.Read(FileBytes, 0, FileBytes.Length)) > 0)
{
Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);
CurrentFileSize += qtdRead;
CurrentProgress = (int)((CurrentFileSize * 100) / FileSize);
UploadSpeed = ((double)CurrentFileSize / (Counter.Elapsed.TotalMilliseconds / 100));
UploadWork.ReportProgress(CurrentProgress);
}
FileStr.Close();
Counter.Stop();
Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
Program.CTasks.ClientSocket.Close();
}
}
catch
{
try
{
Counter.Stop();
FileStr.Close();
Program.CTasks.ClientSocket.Close();
}
catch { }
}
}
您发送的数据太多了...在文件的末尾,FileBytes
将更长的时间完全填满,并且您应该只发送qtdRead
字节。
取代
Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);
跟
Program.CTasks.ClientSocket.Send(FileBytes, 0, qtdRead, 0);
您使用的是缓冲区长度,而不是发送时读取的内容长度。