【求助】C#socket问题
本帖最后由 lizf2019 于 2021-8-23 08:54 编辑源码(方法):发送端: publicvoid 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;
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.");
}
}
接收端:public static void Receive(IPEndPoint ip, string path) {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(ip);
sock.Listen(1);
Socket client = sock.Accept();
byte[] buffer = new byte;
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里写的:
(服务器端会卡死)
传输端:
(报错无法连接)
求大佬指点 你可以先用个工具单独测试服务端或者客户端。另外直接csdn下个例子照着改改就行了
服务器是不是没开端口,先在自己电脑写好接受和发送,在上服务器 小白来袭2 发表于 2021-8-23 09:40
服务器是不是没开端口,先在自己电脑写好接受和发送,在上服务器
服务器端是应怎么写呢 本帖最后由 ordinarysoul 于 2021-8-23 11:02 编辑
把服务器IP或者127.0.0.1换成IPAddress.Any ordinarysoul 发表于 2021-8-23 10:42
我的判断是socket默认的发送缓冲也就是send大小超过默认值,使用setsockopt修改缓冲区大小。
或者客户端加 ...
大佬这个是连接都连不上 lizf2019 发表于 2021-8-23 10:53
大佬这个是连接都连不上
没注意看问题。ipaddress.parse("ip地址")换成IPAddress.Any试试 ordinarysoul 发表于 2021-8-23 11:03
没注意看问题。ipaddress.parse("ip地址")换成IPAddress.Any试试
还是不行{:301_973:} lizf2019 发表于 2021-8-23 11:23
还是不行
端口应该问题不大,建议排查一下,服务器端的监听地址和请求地址确保一致。
你是不是本地测试没问题,挂到服务器端就无法连接了
lizf2019 发表于 2021-8-23 11:23
还是不行
我在本地创建两个项目模拟服务端和客户端,粘贴你的代码,没有任何问题。
客户端地址是127.0.0.1 服务端地址IPAddress.Any
页:
[1]
2