我试图发送文件抛出套接字并做到了...... 唯一出错的是,我只能在localhost中发送大文件(大约10 MB以上)... 我无法在真实的网络中传输更大的文件......任何帮助?
客户端:
byte[] fileNameByte = Encoding.ASCII.GetBytes(shortFileName);
byte[] fileData = File.ReadAllBytes(longFileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
TcpClient clientSocket = new TcpClient(remoteHostIP, remoteHostPort);
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Write(clientData, 0, clientData.GetLength(0));
networkStream.Close();
服务器:
try
{
TcpListener tcpListener = new TcpListener(port);
tcpListener.Start();
while (true)
{
Socket handlerSocket = tcpListener.AcceptSocket();
if (handlerSocket.Connected)
{
string fileName = string.Empty;
NetworkStream networkStream = new NetworkStream(handlerSocket);
int thisRead = 0;
int blockSize = 1024;
Byte[] dataByte = new Byte[blockSize];
lock (this)
{
string folderPath = @"c:\";
handlerSocket.Receive(dataByte);
int fileNameLen = BitConverter.ToInt32(dataByte, 0);
fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
Stream fileStream = File.OpenWrite(folderPath + fileName);
fileStream.Write(dataByte, 4+fileNameLen,(1024-(4+fileNameLen)));
while (true)
{
thisRead = networkStream.Read(dataByte, 0, blockSize);
fileStream.Write(dataByte, 0,thisRead);
if (thisRead == 0)
break;
}
fileStream.Close();
}
if (NewFileRecieved != null)
{
NewFileRecieved(this, fileName);
}
handlerSocket = null;
}
}
}
catch
{
}
答案 0 :(得分:-1)
这听起来可以通过修改app.config(或web.config)文件来解决。这是一个可以修改的条目:
<configuration>
...
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="3600" />
...
</system.web>
</configuration>
其中maxRequestLength
是以KB为单位的最大文件长度。更全面的解释可以在以下网址找到:
http://www.telerik.com/help/aspnet-ajax/upload-uploading-large-files.html
http://www.webdavsystem.com/server/documentation/large_files_iis_asp_net
[编辑] - 从下面的评论中可以看出,这个实际的答案并没有解决问题,而是向使用异步套接字api提出了解决方案。帮助的完整文章可以在这里找到: