Click here to Skip to main content
13,044,371 members (123,412 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I have studying the socket program using c#.
I am writing a simple chatroom with asynchronous socket .
this is code:

//creat the listensocket.
this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
//Start the server.
SocketAsyncEventArgs acceptEventArg = CreateAcceptEventArg();

I take the following math to stop the listenSocket:

internal void StopListening()
          //close every client socket first.
           foreach (UserToken item in clientList)
           // andthen close the listen socket.
           if (this.listenSocket != null)

Tragedy is occurred when "

" is execeted, the application of the chatroom is close auto.
I original idea is stoping listening only not exit the application, when user click the "start listening"
button , it will to relisten. So, there should have some errors i don't know.
Thanks for the good man giving me the answer.
Posted 15-Jul-11 20:33pm
Updated 15-Jul-11 20:41pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

First thing this link is about socket Close method[^]

"For connection-oriented protocols, it is recommended that you call Shutdown before calling the Close method. This ensures that all data is sent and received on the connected socket before it is closed."

Second thing - it is not clear what you ar doing inside CloseClientSocket.

Third thing - when you perform if (this.listenSocket != null), you should also assign it to null after opeations are finished.

And the last and most important - application closes, probably, because some exception happens during socket.Close method execution. You could try to place it inside try-catch statement and read an error message. Maybe this will help to locate and fix the error.
SAKryukov 17-Jul-11 15:32pm
This is the answer, my 5.
OP put replied in two "solutions" (removed but readable), please see.
skv_lviv 17-Jul-11 22:08pm
However I don't see those replies, it looks like they are not available anymore. Will have to wait until there will be update in the original question or some new comment.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 17 Jul 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100