我的意思是用偵听端口的方法

解决方案 »

  1.   

    Server Side
    If you have understood whatever I have described so far, you will easily understand the Server part of the socket application. So far we have been talking about a client making connection to a server and sending and receiving data. On the Server end, the application has to send and receive data. But in addition to adding and receiving data, server has to allow the clients to make connections by listening at some port. Server does not need to know client I.P. addresses. It really does not care where the client is because its not the server but client who is responsible for making connection. Server's responsibility is to manage client connections. On the server side there has to be one socket called the Listener socket that listens at a specific port number for client connections. When the client makes a  connection, the server needs to accept the connection and then in order for the server to send and receive data from that connected client it needs to talk to that client through the socket that it got when it accepted the connection . Following code illustrates how server listens to the connections and accepts the connection:public Socket m_socListener;
    public void StartListening()
    {
     try
     {
    //create the listening socket...
    m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);
    //bind to local IP Address...
    m_socListener.Bind( ipLocal );
    //start listening...
    m_socListener.Listen (4);
    // create the call back for any client connections...
    m_socListener.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
    cmdListen.Enabled = false;
     }
     catch(SocketException se)
     {
    MessageBox.Show ( se.Message );
     }
    }