Question about socket variable declaration

Nov 29 2007 9:04 AM

Hi everybody, I'm making a little program using sockets to send and receive text. I have a class that looks like this:

class SocketClass
{
  ...
   
  public void Listen()
  {
    Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9876);

    listener.Bind(iep);
    listener.Listen(5);
    listener.BeginAccept(new AsyncCallback(AcceptConnection), socket);

    // supposedly here at the end of the procedure the "listener" variable will destroy
}
   
    ...
}

So everything is ok here, but I have a doubt about the variable declaration of the socket.
As far as I know when I declare a variable inside a body procedure, the scope of this variable is just right here and I can't access to it outside the procedure, so if this is ok when I declare a variable like the code above "Socket listener = new Socket..." it means that the "listener" variable will create in the procedure "Listen" and destroy itself in the same procedure, but this is not right becouse I can connect to the socket, so the question is how can I connet to a socket that is listening if the variable "listener" is destroyed at the end of the procedure "Listen" ?

Thanks in advance.


Answers (2)