.net for TCP服务端 && 客户端

关键代码

详细代码请看示例代码html

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的写法则运行正常git

//报错
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipaddress), port);
//正确
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, port);

参考资料

在其上下文中,该请求的地址无效github

示例代码

示例代码c#

相关文章
相关标签/搜索