I'm new to server socket anything and when attempting to create a simple application I ran into this problem. I can connect to the server application just fine as well as reconnect again. But when i disconnect the second time I get an error. Here is my code, I hope someone can help me understand why.
private static TcpListener clientListener;
private static Socket clientSocket;
private static bool running = false;
private static Thread runThread;
static void Main(string[] args){
writeMsg(">> Server started");
waitForConnection();
}
private static void writeMsg(String msg){
Console.WriteLine(msg);
}
private static void run(){
while (running){
try{
byte[] prefBuffer = new byte[100];
int bufferSize = clientSocket.Receive(prefBuffer);
writeMsg(">> Data recieved from client");
for (int i = 0; i < bufferSize; i++){
Console.Write(Convert.ToChar(prefBuffer[i]));
}
}
catch{
writeMsg("Connection Lost");
running = false;
clientListener.Stop();
clientSocket.Close();
waitForConnection();
}
}
runThread.Abort();
}
private static void waitForConnection(){
//This is the where the error is created and it says...
//Cannot access disposed object.
clientListener = new TcpListener(IPAddress.Parse("111.111.111.111"), 7414);
clientListener.Start();
writeMsg(">> Listening for connections...");
try{
clientSocket = clientListener.AcceptSocket();
writeMsg(">> Connection established");
running = true;
startRunThread();
}
catch (Exception e){
writeMsg(String.Format(">> Connection failed\n Error: {0}", e.Message));
}
}
private static void startRunThread(){
runThread = new Thread(new ThreadStart(run));
runThread.Start();
}
As seen in the comments in the above code a get an error saying I cannot access a disposed object even though I reinitialized it? Here is the stack trace
at System.Net.Sockets.Socket.Listen(Int32 backlog)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
at Server.Program.waitForConnection() in ...\Program.cs:line 55