C# socket must be bind before listen, otherwise listen will report an error "An invalid parameter was provided"

//Ready to receive socket requests
//Create a new socket Socket to create a Socket
//Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); This line creates a socket, and its 3 parameters represent Address family, socket type and protocol. The address family indicates whether to use IPv4 or IPv6. In this example, IPv4 is used, that is, InterNetwork

 Socket listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //Bind指定套接字的IP和端口
        //listenfd.Bind(ipEp) 将给listenfd套接字绑定IP和端口。 示例程序中绑定的是本地地址“127.0.0.1”和1234号端口。 127.0.0.1是回送地址, 指本地机, 一般用于测试。 读者也可以设置成真实的IP地址, 然后在两台电脑上分别运行客户端和服务端程序。
  IPAddress ipAdr = IPAddress.Parse("127.0.0.1");//根据IP地址创建IPAddress对象,如IPAddress.Parse("192.168.1.1")
  IPEndPoint ipEp = new IPEndPoint(ipAdr, 1234);//用IPAddress指定的地址和端口号初始化
        //服务端通过listenfd.Listen(0) 开启监听, 等待客户端连接。 参数backlog指定队列中最多可容纳等待接受的连接数, 0表示不限制
 listenfd.Bind(ipEp);//忘记bind就会报错“提供了一个无效的参数”
 listenfd.Listen(10);
 Console.WriteLine("[服务器]启动成功");

**

listenfd.Bind(ipEp);//If you forget bind, you will get an error "An invalid parameter was provided"! ! ! Record it

**

Guess you like

Origin blog.csdn.net/yunxiang1224/article/details/109808662