Socket Listen for single connection

Y

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.
 
Y

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();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top