关键代码
详细代码请看示例代码
Service
//创建套接字
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipaddress), port);
//也可以使用IPAddress.Any,监听所有网络接口上的客户端活动
//https://docs.microsoft.com/en-us/dotnet/api/system.net.ipaddress.any?view=netframework-4.7.2
//一般来说,服务端套接字都是直接bind端口,不会显式指明ip地址
//否则切换了服务器还需要修改,或者也可以动态获取IP,但是没必要
IPEndPoint ipe2 = new IPEndPoint(IPAddress.Any, port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//https://www.codeproject.com/Articles/117557/Set-Keep-Alive-Values
//http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html
SetTcpKeepAlive(socket, 600000, 1000);
//绑定端口和IP
socket.Bind(ipe);
//设置监听数
socket.Listen(10);
//连接客户端
await AsyncAccept(socket);
Client
//端口及IP
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipaddress), port);
//创建套接字
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//开始连接到服务器
client.BeginConnect(ipe,async asyncResult =>
{
client.EndConnect(asyncResult);
//向服务器发送消息
await AsynSend(client, "你好我是客户端");
await AsynSend(client, "第一条消息");
await AsynSend(client, "第二条消息");
//接受消息
await AsynRecive(client);
}, null);
报错
1.在其上下文中,该请求的地址无效
遇到这个问题是在正式服务器上,在测试服务器上运行良好,所以考虑是机器或者网络配置的问题,包括出入站规则、防火墙、端口映射、端口转向等
不是太懂运维的内容,所以对代码进行了修改
把具体的IP改为了IPAddress.Any的写法则运行正常
//报错
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipaddress), port);
//正确
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, port);