-1

I am making a simple client to server set up in C#. I have two separate programs for both. I am trying to have my server have the ability to turn online or offline through the use of a checkbox. I have looked on the web and found that socket.blocking could be used? But I tried implementing it and it doesn't work. I get an error when I check the textBox to turn the server offline saying "Object reference not set to an instance of an object.". Here's the code in my checkbox function:

if (checkBox1.Checked)
{
    server.Blocking = true;
}
else
{
    server.Blocking = false;
}

Am I going about this the right way? I don't want the server to turn off but instead become unavailable to the client. Which is why I decided a blocking method would be best?

Any help would be greatly appreciated Thank you

Lloyd
  • 425
  • 2
  • 9
  • 26

1 Answers1

1

The server should be in a Listen or BeginListen call. You want to stop listening when the user unchecks the box on the server UI. Use the Stop method if you are using TcpServer. With Socket, use Shutdown followed by a Close. There may be exceptions in whatever routine or thread is doing the listening.

With both classes, you are essentially tearing everything down. There isn't a simple 'stop listening for now' property. You need to tear the socket down when they uncheck the box, and then build a new Socket or TcpServer from scratch when they check the checkbox again. The closest thing would be to keep accepting connections, but immediately close them as soon as anyone connects. I don't like that approach.

Correct protocol chatter during teardown is left as an exercise :) IOW, consider searching for how to correctly tear down Socket or TcpServer objects and how to finish pending reads and writes.

H^2

bigh_29
  • 2,169
  • 21
  • 19