c#套接字发送文件
我正在尝试使用c#套接字发送文件,c#,file,sockets,C#,File,Sockets,我正在尝试使用SendFile方法 服务器代码: TcpListener listener; TcpClient cl; private void Form1_Load(object sender, EventArgs e) { listener = new TcpListener(IPAddress.Any, 10); listener.Start(); cl = listener.AcceptTcpClient(
SendFile
方法
服务器代码:
TcpListener listener;
TcpClient cl;
private void Form1_Load(object sender, EventArgs e)
{
listener = new TcpListener(IPAddress.Any, 10);
listener.Start();
cl = listener.AcceptTcpClient();
}
我的问题是:我应该如何把文件放在另一边?我不想只使用networkstream纯套接字。
任何帮助都将被显示文件将以字节形式发送。没有标题或任何内容。只有文件字节 您可能应该使用
file.Create
打开要将此文件另存为的文件,然后使用newnetworkstream(mySocket).CopyTo(myFile)
我不想使用networkstream
这就更难了。您自己编写一个流复制循环。除了以下代码外,您还必须关闭发送套接字才能退出while循环。blockCtr和totalReadBytes仅用于诊断
private void btnReceive_Click(object sender, EventArgs e)
{
const int arSize = 100;
byte[] buffer = new byte[arSize];
string outPath = @"D:\temp\rxFile.jpg";
Stream strm = new FileStream(outPath, FileMode.CreateNew);
try
{
listener = new TcpListener(IPAddress.Any, 10);
listener.Start();
cl = listener.AcceptTcpClient();
SocketError errorCode;
int readBytes = -1;
int blockCtr = 0;
int totalReadBytes = 0;
while (readBytes != 0)
{
readBytes = cl.Client.Receive(buffer, 0, arSize, SocketFlags.None, out errorCode);
blockCtr++;
totalReadBytes += readBytes;
strm.Write(buffer, 0, readBytes);
}
strm.Close();
MessageBox.Show("Received: " + totalReadBytes.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
这方面的基本方法是:
- 开放连接
- 从连接读取
- 写入输出流(内存/文件/任何内容)
NetworkStream
我不想只使用networkstream纯套接字
让我们再看一下Stream.CopyTo的内部结构:
private void InternalCopyTo(Stream destination, int bufferSize)
{
int num;
byte[] buffer = new byte[bufferSize];
while ((num = this.Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, num);
}
}
和NetworkStream.Write
:
public override void Write(byte[] buffer, int offset, int size)
{
// Insert Lots and Lots of checks and safety's here:
streamSocket.Send(buffer, offset, size, SocketFlags.None);
}
还请注意,NetworkStream
负责正确的连接处理、正确关闭连接等
简而言之,您可能不想使用NetworkStream
的原因只有一个:我想完全同步,因为CopyTo实现是同步的。如果您使用的是async
/wait
,那么即使是这样,也有很大的争议。这适用于服务器环境中的高性能(c.q.大量连接)
如果是这种情况,您可能希望从以下示例代码开始:
public override void Write(byte[] buffer, int offset, int size)
{
// Insert Lots and Lots of checks and safety's here:
streamSocket.Send(buffer, offset, size, SocketFlags.None);
}