Share via


C# Stop Socket.Accept()

Question

Saturday, March 17, 2012 1:23 PM

         sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());            string stlocalIP = localIPs[0].ToString();            sck.Bind(new IPEndPoint(IPAddress.Parse(stlocalIP), 1234));            sck.Listen(100);               while (true)            {                           Socket accepted = sck.Accept(); // <waits here...???                    Buffer = new byte[accepted.SendBufferSize];                int bytesRead = accepted.Receive(Buffer);                byte[] formatted = new byte[bytesRead];

Hi,

I have a server - client application. In server side i set my socket connection like up. I listen incoming packets with thread functions and monitor them all.Everythınk works. But i cant find a way to finish the application. What i cannnot is write a button click event code to cancel listening and free "Socket accepted = sck.Accept(); " line. Thanks,

Mustafa

All replies (2)

Saturday, March 17, 2012 5:27 PM ✅Answered | 3 votes

Did you try to close or dispose the socket? I suppose that he will stop the accept!? Just catch the exception which is thrown

mySocket.Shutdown(SocketShutdown.Both);
mySocket.Close();

http://stackoverflow.com/questions/3601521/c-sharp-socket-close-should-i-still-call-dispose


Saturday, March 17, 2012 8:11 PM

Thanks Mr. Jochen yes it worked.