Home All Groups Group Topic Archive Search About

Socket Listen for single connection

Author
31 Mar 2006 9:18 PM
yofnik
I am writing an application that simulates a TCP device that only
accepts one connection at a time. For my application, I would like
connection requests to fail if one already exists. So far I have the
following code:

   IPAddress ip = Dns.Resolve("localhost").AddressList[0];
   Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

  ProtocolType.Tcp);
   IPEndPoint ep = new IPEndPoint(ip, 2323);
   s.Bind(ep);
   s.Listen(0);

   while(true)
   {
      Socket s1 = s.Accept();
      s1.Receive(request);
      ....
      s1.Close();
   }

It seems that Listen(0) does not work as expected. If I open a client
to this application and leave it idle, and then open up a second
client, it waits for the first client to finish. If I open a third
client, the conneciton fails as I would like it to. It seems to me that

Listen(0) is behaving as I expect Listen(1) should.

How can I prevent the second from waiting? I want it to fail
immediately. Any suggestions?

Thanks.

Author
1 Apr 2006 9:22 AM
Vadym Stetsyak
Hello, yof***@comcast.net!

y>    IPAddress ip = Dns.Resolve("localhost").AddressList[0];
y>    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

y>   ProtocolType.Tcp);
y>    IPEndPoint ep = new IPEndPoint(ip, 2323);
y>    s.Bind(ep);
y>    s.Listen(0);

y>    while(true)
y>    {
y>       Socket s1 = s.Accept();
y>       s1.Receive(request);
y>       ....
y>       s1.Close();
y>    }

y> It seems that Listen(0) does not work as expected. If I open a client
y> to this application and leave it idle, and then open up a second
y> client, it waits for the first client to finish. If I open a third
y> client, the conneciton fails as I would like it to. It seems to me that

y> Listen(0) is behaving as I expect Listen(1) should.

y> How can I prevent the second from waiting? I want it to fail
y> immediately. Any suggestions?

If you use .NET 2.0 you can use conditional accept via Socket.BeginAccept. In the callback you can determine what to do: if there is already one open connection you will not accept the incomming connection.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Author
3 Apr 2006 2:01 PM
yofnik
I don't know what I was thinking. All I had to do was close the
listening socket and reopen it when I am ready for another connection.
The following code accomplishes exactly what I was looking for:


    IPAddress ip = Dns.Resolve("localhost").AddressList[0];
    IPEndPoint ep = new IPEndPoint(ip, 2323);

    while(true)
    {
       Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
       s.Bind(ep);
       s.Listen(0);
       Socket s1 = s.Accept();
       s.Close();
       s1.Receive(request);
       ....
       s1.Close();
    }

AddThis Social Bookmark Button