客户端IPEndPoint无法使用IPAddress.Any?

时间:2013-03-20 03:32:43

标签: c# asyncsocket

我一直在学习一些套接字编程,我创建了一个只监听并返回数据的异步服务器。

但我在这里遇到问题,我在服务器上使用IPEndPoint和IPEndPoint(IPAddress.any,port),我也在客户端做同样的事情。运行服务器和客户端时,我使用try catch,客户端返回其异常,如此

“请求的地址在其上下文0.0.0.0:port”

中无效

下面是代码:

Server.cs

      Public void Listen()
      {
        IPEndPoint IpEnd = new IPEndPoint(IPAddress.Any, 11000);

        Console.WriteLine("Create new socket");
        mainSocket = new Socket(AddressFamily.InterNetwork,
                       SocketType.Stream,ProtocolType.IP);

        Console.WriteLine("Bind the socket");
        mainSocket.Bind(IpEnd);

        Console.WriteLine("Listening to socket");
        mainSocket.Listen(10);

        Console.WriteLine("Waiting Connection");
        mainSocket.BeginAccept(new AsyncCallback(AcceptConnect), null);
      }
      protected void AcceptConnect(IAsyncResult ar)
      {
        try
        {
            Socket client = mainSocket.EndAccept(ar);
            SessionData session = new SessionData();
            Console.WriteLine("Connection Accepted, waiting for Data");
            Console.WriteLine("Waiting a new Connection");
            mainSocket.BeginAccept(new AsyncCallback(AcceptConnect), null);
            try{
                session.clientSocket = client;
                client.BeginReceive(session.buffer,0,SessionData.buffersize,0, 
                                    new AsyncCallback(ReceiveData), session);
            }catch(Exception e){
                client.Send(ASCIIEncoding.Default.GetBytes(e.Message));
                Console.WriteLine(e.Message);
            }
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
      }

Client.cs

    public void ClientConnect()
    {

        // Create a TCP/IP socket.
        Socket client = new Socket(AddressFamily.InterNetwork, 
                        SocketType.Stream, ProtocolType.Tcp);

        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 11000);

        // Connect to the remote endpoint.
        client.BeginConnect(remoteEP, new AsyncCallback(ConnectServer), client);
    }
    public void ConnectServer(IAsyncResult ar) 
    {
        try
        {
            Socket client = (Socket)ar.AsyncState;
            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}", 
                             client.RemoteEndPoint.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

我的问题是:

  1. 客户端是否需要指向一个IPAddress?
  2. 我只是在服务器上使用了错误的代码吗?

1 个答案:

答案 0 :(得分:1)

客户端需要指向特定的IP地址(即192.168.1.101或类似的东西),不能将数据包发送到IP 0.0.0.0。服务器可以接受IP.Any的原因是它正在侦听本地计算机上的所有IP地址,其表示为0.0.0.0。