Question

I have the following code for a server:

namespace Test
{
    public class TCPListener
    {
        public static void Main()
        {
            TcpListener listener = null;
            TcpClient client = null;
            NetworkStream stream = null;
            BinaryWriter writer = null;

            try
            {
                listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), 5000);
                listener.Start();

                while (true)
                {
                    using (client = listener.AcceptTcpClient())
                    {
                        using (stream = client.GetStream())
                        {    
                            writer = new BinaryWriter(stream);
                            writer.Write("The message was received!");
                        }
                    }
                }
            }
            catch (SocketException)
            {
                //Catch socket exception
            }
        }
    }
}

Now, if I put this code in a console application and use telnet, I receive "The message was received" message on the command prompt. Now, I copied and pasted this code (changing the namespace) into a web application as a class. The web application solution was deployed on port 5000. Apart from the server, it also contains a number of pages which the user can browse.

Unfortunately, if I go to telnet and type "telnet 127.0.0.1 5000", a connection is achieved, however I don't receive anything. What do you think is the problem? How can I solve it?

Was it helpful?

Solution

Mathew,

As aluded to by the emeritus mr skeet, you are only catching half the equation. You need to then instantiate the class and call the Main() method.

Here's how you could do that:

TCPListener tcpListener = new TCPListener(); 
tcpListener.Main();

Try that in your main point of setup in your web based solution (controller action or page load code behind). Also, change the method signature on Main (remove the static).

Also, you seem to be calling your class inside itself:

listener = new TcpListener();

That is gonna cause big problems... I would suggest a little refactoring and a rethink about how Main works. Your 1st major win would be to rename the example class above away from TCPListener, to something else as there appears to be a collision going on there.

[EDIT] To save reading the comments below. The final solution that Matthew took was to go back to the console solution and invoke it from the webapp. This way he scored a couple of wins:

  • Existing console app had been tested and worked
  • Looser coupling of moving parts
  • Extensibility to use in other projects
  • Ability to implement and move onto other time sensitive elements of project

The takeaway here is, "always examine the options and think beyond a single solution to solve a problem"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top