Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# socket
I create a aid thread to listen the connection from client,but I failed when I close the Socket.Can you help me?
My code as follow:
 
class Listener{
   Thread  listenThread;
   Socket  listenSocket;
   bool isListeningContinued=false;
   public Listener(){
     listenSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
     listenThread=new Thread(new ThreadStart(Listening));
   }
   public void Start(IPEndPoint ipEP){
      listenSocket.Bind(ipEP);
      listenSocket.Listen(100);
      isListeningContinued=true;
      listenThread.Start();
   }
   public void Stop(){
       isListeningContinued=false;
       listenSocket.ShutDown(SocketShutdown.Both);
       listenSocket.Close();
   }
   void Listening(){
      while(isListeningContinued){
          Socket socket=listenSocket.Accept();
          //Do something to receive the data from client
      }
   }
}
I can Start the listen action correctly,but I failed to Stop the listen action , specifically I can't Stop the Accept action running in the aid thread. How can I stop the Accept action from the main thread? Thanks.
Posted 30-Aug-12 4:28am
lzeng19861.3K
Edited 30-Aug-12 4:31am
(no name)81.2K
v2
Comments
Wes Aday at 30-Aug-12 10:55am
   
What I have done in the past is connect to myself so the accept drops through and then issue a stop command through the connection.

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

  Print Answers RSS
0 OriginalGriff 505
1 Maciej Los 325
2 Richard MacCutchan 265
3 Mathew Soji 220
4 BillWoodruff 210
0 OriginalGriff 8,804
1 Sergey Alexandrovich Kryukov 7,457
2 DamithSL 5,689
3 Maciej Los 5,279
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web03 | 2.8.1411028.1 | Last Updated 30 Aug 2012
Copyright © CodeProject, 1999-2014
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