Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have studying the socket program using c#.
I am writing a simple chatroom with asynchronous socket .
this is code:


C#
...
//creat the listensocket.
this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

this.listenSocket.Bind(localEndPoint);

//Start the server.
listenSocket.Listen(ServerSocketSetting.Backlog);

SocketAsyncEventArgs acceptEventArg = CreateAcceptEventArg();
this.listenSocket.AcceptAsync(acceptEventArg);


I take the following math to stop the listenSocket:

C#
internal void StopListening()
       {
          //close every client socket first.
           foreach (UserToken item in clientList)
           {
               this.CloseClientSocket(item.receiveSendEnventArg);
           }
           // andthen close the listen socket.
           if (this.listenSocket != null)
           {
               //this.listenSocket.Shutdown(SocketShutdown.Both);
               this.listenSocket.Close();
               //this.listenSocket.Disconnect(true);
           }
       }



Tragedy is occurred when "
MIDL
this.listenSocket.Close();

" 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
Updated 15-Jul-11 20:41pm
v4

1 solution

First thing this link is about socket Close method

http://msdn.microsoft.com/en-us/library/wahsac9k.aspx[^]

"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.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-Jul-11 15:32pm    
This is the answer, my 5.
OP put replied in two "solutions" (removed but readable), please see.
--SA
skv_lviv 17-Jul-11 22:08pm    
Thanks.
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900