我正在使用套接字处理从桌面应用程序到 Windows 手机应用程序的 sendig 文件。
我已经开发了桌面套接字服务器应用程序和 Windows Phone 应用程序(套接字客户端),两者都适用于小于 1MB 的文件,这意味着我可以将小于 1MB 的文件从桌面应用程序传输到 Windows Phone 应用程序。
现在我的问题是发送大文件导致应用程序崩溃,我已经调试了应用程序,但它会在一些迭代后挂起。
请检查以下代码片段以了解 Windows Phone 端的文件接收逻辑。
代码 :
public string Receive()
{
string response = "Operation Timeout";
int bytestrn = 0;
int cnt = 0;
byte[] data = new byte[2048 * 5000];
if (socketClient != null)
{
SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
socketAsyncEventArgs.RemoteEndPoint = socketClient.RemoteEndPoint;
socketAsyncEventArgs.SetBuffer(new Byte[MAX_BUFFER_SIZE*20000], 0, MAX_BUFFER_SIZE*20000);
socketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object sender, SocketAsyncEventArgs e)
{
cnt++;
if (e.SocketError == SocketError.Success)
{
try
{
bytestrn += e.BytesTransferred;
if (e.BytesTransferred > 0)
{
if (bytestrn >= 2501829)
{
Buffer.BlockCopy(e.Buffer, 0, data, bytestrn - e.BytesTransferred, e.BytesTransferred);
int fileNameLen = BitConverter.ToInt32(data, 0);
string fileName = Encoding.UTF8.GetString(data, 4, fileNameLen);
IsoFileName = fileName;
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (BinaryWriter writeFile = new BinaryWriter(new IsolatedStorageFileStream(IsoFileName, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
{
writeFile.Write(data, 4 + fileNameLen, bytestrn - 4 - fileNameLen);
writeFile.Close();
}
clientDone.Set();
}
else
{
if (cnt == 1)
{
Buffer.BlockCopy(e.Buffer, 0, data, 0, e.BytesTransferred);
//e.Buffer.CopyTo(data, 0);
}
else
{
Buffer.BlockCopy(e.Buffer, 0, data, bytestrn - e.BytesTransferred, e.BytesTransferred);
//e.Buffer.CopyTo(data, bytestrn - e.BytesTransferred);
}
clientDone.Reset();
socketClient.ReceiveAsync(e);
clientDone.WaitOne();
}
string test = "if";
}
else
{
clientDone.Set();
string test = "else";
}
//clientDone.Set();
}
catch (Exception exp)
{
string hi = "hi";
}
}
else
{
response = e.SocketError.ToString();
}
clientDone.Set();
});
clientDone.Reset();
socketClient.ReceiveAsync(socketAsyncEventArgs);
clientDone.WaitOne();
}
else
{
response = "Socket is not initialized";
} // end of: if (socketClient != null)
return response;
}
请尽快回复...
谢谢。