我想使用套接字发送文件..它的工作与几个字节文件没有更多...如何解决这个问题? 这是一个客户端/服务器程序 我试图发送至少50 MB。发送带有套接字的文件c#客户端/服务器
的客户端,发送:
System.Net.Sockets.TcpClient tcpClient = new
System.Net.Sockets.TcpClient();
tcpClient.Connect(recipientIP, FTPPORTNO);
int BufferSize = tcpClient.ReceiveBufferSize;
NetworkStream nws = tcpClient.GetStream();
FileStream fs;
fs = new FileStream(filename, FileMode.Open,
FileAccess.Read);
byte[] bytesToSend = new byte[fs.Length];
int numBytesRead = fs.Read(bytesToSend, 0,
bytesToSend.Length);
int totalBytes = 0;
for (int i = 0; i <= fs.Length/BufferSize; i++)
{
//---send the file---
if (fs.Length - (i*BufferSize) > BufferSize)
{
nws.Write(bytesToSend, i*BufferSize,
BufferSize);
totalBytes += BufferSize;
}
else
{
nws.Write(bytesToSend, i*BufferSize,
(int) fs.Length - (i*BufferSize));
totalBytes += (int) fs.Length - (i*BufferSize);
}
fs.Close();
}
的Recieving代码:
try
{
//---get the local IP address---
System.Net.IPAddress localAdd =
System.Net.IPAddress.Parse(
ips.AddressList[0].ToString());
//---start listening for incoming connection---
System.Net.Sockets.TcpListener listener = new
System.Net.Sockets.TcpListener(localAdd,
FTPPORTNO);
listener.Start();
//---read incoming stream---
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream nws = tcpClient.GetStream();
//---delete the file if it exists---
if (File.Exists("c:\\temp\\" + filename))
{
File.Delete("c:\\temp\\" + filename);
}
//---create the file---
fs = new System.IO.FileStream("c:\\temp\\" + filename,
FileMode.Append, FileAccess.Write);
int counter = 0;
int totalBytes = 0;
do
{
//---read the incoming data---
int bytesRead = nws.Read(data, 0,
tcpClient.ReceiveBufferSize);
totalBytes += bytesRead;
fs.Write(data, 0, bytesRead);
//---update the status label---
ToolStripStatusLabel1.Text = "Receiving " +
totalBytes + " bytes....";
Application.DoEvents();
counter += 1;
} while (nws.DataAvailable);
ToolStripStatusLabel1.Text = "Receiving " + totalBytes
+ " bytes....Done.";
fs.Close();
tcpClient.Close();
listener.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
服务器代码:
public void SendMessage (string message)
{
//---adds a linefeed char---
message += "\n";
try
{
//---send the text---
System.Net.Sockets.NetworkStream ns;
lock (client.GetStream())
{
ns = client.GetStream();
byte[] bytesToSend =
System.Text.Encoding.ASCII.GetBytes(message);
//---sends the text---
ns.Write(bytesToSend, 0, bytesToSend.Length);
ns.Flush();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
什么想法?
您是否试图做到这一点? [检查此](http://code.msdn.microsoft.com/windowsdesktop/Fixed-size-large-file-dfc3f45d) –
请编辑您的问题,并格式化代码。你现在拥有的东西几乎是不可读的。 –
好吧......我应该把它分成块或什么东西? – user3379482