【发布时间】:2014-06-19 22:40:03
【问题描述】:
我正在尝试使用套接字发送文件..它不再使用几个字节的文件...如何解决这个问题? 这是一个客户端/服务器程序 我正在尝试发送至少 50 MB。
客户端-发送:
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();
}
接收代码:
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());
}
}
有什么想法吗?
【问题讨论】:
-
你尝试过异步吗? check this
-
请编辑您的问题并格式化代码。你现在所拥有的几乎无法阅读。
-
嗯……我应该把它分成块还是什么?
-
我用空格格式化了你的代码(缩进)。下次你发布一些代码时,请确保它正确缩进。