通过TCP插座发送几个MB文件时,如何修复死锁?
我想通过RAW TCP套接字发送文件。 当我发送小于定义缓冲区的文件时,它可以正常工作。 当我发送10MB文件和TCP没有延迟选项时,服务器将挂在读取最后一块上。 当我一次发送该文件(缓冲区大小增加)时,它永远不会发生。 这是我的代码。
客户端是Xamarin表单,服务器是C ++/CLI。
我在想比赛状况,僵局。
客户端
private async Task SendBigFile(Stream stream)
{
using (var bw = new BinaryWriter(this.ns, Encoding.UTF8, true))
{
const int bufferSize = 65535;
long bytesLeft = stream.Length;
while (bytesLeft > 0)
{
var dataSize = (int)Math.Min(bytesLeft, bufferSize);
var data = new byte[dataSize];
var bytesRead = await stream.ReadAsync(data, 0, dataSize);
if (bytesRead != 0)
{
bw.Write(data, 0, bytesRead);
bw.Flush();
bytesLeft -= bytesRead;
}
else
break;
}
}
服务器
void receiveBigFile(unsigned int length, System::IO::Stream^ stream)
{
const System::Int64 bufferSize = 65535;
System::Int64 bytesLeft = length, bytes = 0;
System::IO::BinaryReader^ br = nullptr;
try
{
br = gcnew System::IO::BinaryReader(this->ns, System::Text::Encoding::UTF8, true);
while (bytesLeft > 0)
{
System::Int32 dataSize = System::Math::Min(bytesLeft, bufferSize);
array<System::Byte>^ data = gcnew array<System::Byte>(dataSize);
System::Int64 bytesRead = br->Read(data, 0, data->Length);
if (bytesRead != 0)
{
stream->Write(data, 0, bytesRead);
bytesLeft -= bytesRead;
}
else
break;
}
}
finally
{
if (br != nullptr)
{
br->Close();
}
}
}
I'd like to send file via raw tcp socket.
When I send files smaller than defined buffer, it works.
When I send 10MB files and tcp no delay option is on, server hangs on reading last chunk.
It never happen when I send that file at once(increasing buffer size).
Here is my code.
Client is Xamarin Forms, server is c++/cli.
I'm thinking of race conditions, deadlocks.
Client
private async Task SendBigFile(Stream stream)
{
using (var bw = new BinaryWriter(this.ns, Encoding.UTF8, true))
{
const int bufferSize = 65535;
long bytesLeft = stream.Length;
while (bytesLeft > 0)
{
var dataSize = (int)Math.Min(bytesLeft, bufferSize);
var data = new byte[dataSize];
var bytesRead = await stream.ReadAsync(data, 0, dataSize);
if (bytesRead != 0)
{
bw.Write(data, 0, bytesRead);
bw.Flush();
bytesLeft -= bytesRead;
}
else
break;
}
}
Server
void receiveBigFile(unsigned int length, System::IO::Stream^ stream)
{
const System::Int64 bufferSize = 65535;
System::Int64 bytesLeft = length, bytes = 0;
System::IO::BinaryReader^ br = nullptr;
try
{
br = gcnew System::IO::BinaryReader(this->ns, System::Text::Encoding::UTF8, true);
while (bytesLeft > 0)
{
System::Int32 dataSize = System::Math::Min(bytesLeft, bufferSize);
array<System::Byte>^ data = gcnew array<System::Byte>(dataSize);
System::Int64 bytesRead = br->Read(data, 0, data->Length);
if (bytesRead != 0)
{
stream->Write(data, 0, bytesRead);
bytesLeft -= bytesRead;
}
else
break;
}
}
finally
{
if (br != nullptr)
{
br->Close();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论