1
Answer

Form thread seems to hang, maybe a threading problem?

Ask a question
JR

JR

13y
4.4k
1
Hello,

I am building a server class but I have some difficulties.

When I declare the server in form_load, the form is shown but hangs....

--------------------------------------------------------------------
Server code:

[CODE]
 class ServerThreadPool
  {
  //Declaration of the TcpListener
  private TcpListener client;

  //Constructor
  public ServerThreadPool()
  {
  IPEndPoint IpAdress = new IPEndPoint(IPAddress.Any, 8000);

  client = new TcpListener(IpAdress);
  client.Start();

  Trace.WriteLine("Waiting for clients...");

  while (true)
  {
  while (!client.Pending())
  {
  Thread.Sleep(1000);
  }

  ConnectionThread newconnection = new ConnectionThread();
  newconnection.threadListener = this.client;
  ThreadPool.QueueUserWorkItem(new WaitCallback(newconnection.HandleConnection));
  }
  }
  }


  class ConnectionThread
  {
  public TcpListener threadListener;
  private static int connections = 0;

  public void HandleConnection(object state)
  {
  int recv;
  byte[] data = new byte[1024];

  TcpClient client = threadListener.AcceptTcpClient();
  NetworkStream ns = client.GetStream();

  connections++;

  Trace.WriteLine(connections, "New client accepted: active connections");

  string welcome = "Lets get rocking :) ";

  data = Encoding.ASCII.GetBytes(welcome);
  ns.Write(data, 0, data.Length);

  while (true)
  {
  data = new byte[1024];
  recv = ns.Read(data, 0, data.Length);
  if (recv == 0)
  break;

  ns.Write(data, 0, recv);
  }

  ns.Close();
  client.Close();

  connections = connections - 1;

  Trace.WriteLine(connections, "Client disconnected: active connections");
  }
  }
[/CODE]
_______________________________________________________________________

Form code:

public partial class serverUI : Form
  {
  public serverUI()
  {
  InitializeComponent();
  }

  private void serverUI_Load(object sender, EventArgs e)
  {
  ServerThreadPool STP = new ServerThreadPool();

  }

  }
__________________________________________________________________________

This code is taken from a console program and I think I know what is causing the problem:

It looks like the STP is started on the form thread, because STP enters an endless loop, the form does not respond anymore.

How can I start the server (client.pending on its own thread)?

Or is there something else wrong?

thanks in advance.

BTW: How can I format code the right way (in a block)?? I've tried [code] and [/code] but this does not work.

Answers (1)