好友
阅读权限25
听众
最后登录1970-1-1
|
本帖最后由 lizf2019 于 2021-8-23 08:54 编辑
源码(方法):发送端:[C#] 纯文本查看 复制代码 public void Send(IPEndPoint ip, string path)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ip);
using (FileStream reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
{
long send = 0L, length = reader.Length;
sock.Send(BitConverter.GetBytes(length));
string fileName = Path.GetFileName(path);
sock.Send(Encoding.Default.GetBytes(fileName));
Console.WriteLine("Sending file:" + fileName + ".Plz wait...");
byte[] buffer = new byte[BufferSize];
int read, sent;
//断点发送 在这里判断设置reader.Position即可
while ((read = reader.Read(buffer, 0, BufferSize)) != 0)
{
sent = 0;
while ((sent += sock.Send(buffer, sent, read, SocketFlags.None)) < read)
{
send += (long)sent;
//Console.WriteLine("Sent " + send + "/" + length + ".");//进度
}
}
Console.WriteLine("Send finish.");
}
}
接收端:[C#] 纯文本查看 复制代码 public static void Receive(IPEndPoint ip, string path)[/b][/size][size=6][b] {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(ip);
sock.Listen(1);
Socket client = sock.Accept();
byte[] buffer = new byte[BufferSize];
client.Receive(buffer);
long receive = 0L, length = BitConverter.ToInt64(buffer, 0);
string fileName = Encoding.Default.GetString(buffer, 0, client.Receive(buffer));
Console.WriteLine("Receiveing file:" + fileName + ".Plz wait...");
using (FileStream writer = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.Write, FileShare.None))
{
int received;
//断点接受 在这里判断设置writer.Position即可
while (receive < length)
{
received = client.Receive(buffer);
writer.Write(buffer, 0, received);
writer.Flush();
receive += (long)received;
Console.WriteLine("Received " + receive + "/" + length + ".");//进度
}
}
Console.WriteLine("Receive finish.");
}
} 服务器端我是在form_load里写的:
(服务器端会卡死)
传输端:
(报错无法连接)
求大佬指点
|
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|