A simple server question

  • Thread starter Thread starter Ray Mitchell
  • Start date Start date
R

Ray Mitchell

Hello,

I've inherited the following code and am trying to get it
to work. As I understand it's purpose, it creates a
server, listens for a client to connect, does some work
with the client, then loops back around and listens for
the client to reconnect again in case it should become
disconnected. If the client never disconnects it just
sits there waiting forever.

Although the code does seem to work I get the following
errors the first few times through the loop each time
after the client connects, then it settles down and
resumes listening properly. I'm not sure what is going on
since I'm new to this networking business but all-in-all
the way this is implemented seems like a kluge to me. All
suggestions of a better way to do this are welcome.

Thanks,
Ray Mitchell

Output from first iteration:

Starting listener...
Client connected...

Output from next few iterations after client work is done:

Starting listener...
Exception2: Not listening. Please call the Start() method.
Starting listener...
Exception2: Not listening. Please call the Start() method.
Starting listener...
Exception2: Not listening. Please call the Start() method.
Starting listener...
Exception2: Not listening. Please call the Start() method.
....
....
....
Starting listener...
Client connected...


The Code:

using System;
using System.Net;
using System.Net.Sockets;

class Class1
{
[STAThread]
static void Main(string[] args)
{
IPAddress ipAddress = Dns.GetHostByName
("MYHOST").AddressList[0];
TcpListener server = null;

while (true)
{
try
{
try
{
Console.WriteLine("Starting listener...");
server = new TcpListener(ipAddress, 6007);
server.Start();
}
catch (Exception e1)
{
}
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected...");
// Do work with client here...
}
catch (Exception e2)
{
Console.WriteLine("Exception2: " + e2.Message);
}
}
}
}
 
HI Ray,

Why do you repeately create and start a new server on each iteration?
I would try this:


class Class1
{
[STAThread]
static void Main(string[] args)
{
IPAddress ipAddress = Dns.GetHostByName
("MYHOST").AddressList[0];
TcpListener server = null;

try
{
Console.WriteLine("Starting listener...");
server = new TcpListener(ipAddress, 6007);
server.Start();
}
catch (Exception e1)
{
}

while (true)
{
try{
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected...");
// Do work with client here...
}
catch (Exception e2)
{
Console.WriteLine("Exception2: " + e2.Message);
}
}
}


} //method
} //class


Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top