IITmadras
IITmadras

Reputation: 21

Telnet Server in C# :AsyncConnection in C#

I am writing a telnet server When i Execute the following program my program is exiting and it is displaying content in only 1 cmd.I have used TCP ASynchronously my content is not displaying on 2cmd .Please help me regarding this issue.

public void Start()
{
    Int32 port = 21;
    IPAddress localAddr = IPAddress.Parse("127.0.0.1");
    server = new TcpListener(localAddr, port);
    server.Start();
    Byte[] bytes = new Byte[256];
    Console.WriteLine("Listening...");
    StartAccept();
}

private void StartAccept()
{
    // listener.BeginAcceptTcpClient(OnAccept, listener);

    server.BeginAcceptTcpClient(HandleAsyncConnection, server);
}

private void HandleAsyncConnection(IAsyncResult res)
{ 
    String data = null;
    TcpListener listener = (TcpListener)res.AsyncState;

     //listen for new connections again
     TcpClient client = server.EndAcceptTcpClient(res);
     Byte[] bytes = new Byte[256];
     while (true)
     { 
        server.Start();
        // TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Connected!");
        data = null;
        NetworkStream stream = client.GetStream();
        int b, i, a;
        string str = null;
        string str1 = null;
        string str3 = null;
        int k = 0;
        int c = 0;
        if (stream.CanWrite)
        {
            if (c == 0)
            {
                `enter code here`
                byte[] Mybuff = Encoding.ASCII.GetBytes("Please Enter USer ID and Password");
                stream.Write(Mybuff, 0, Mybuff.Length);
                //StartAccept();
                c++;
            }
            else 
            {
                byte[] Mybuff = Encoding.ASCII.GetBytes("Please Enter USer ID and Password");
                stream.Write(Mybuff, 0, Mybuff.Length);
                StartAccept();
            }
        }
    }
}

Upvotes: 0

Views: 1099

Answers (2)

ChrisBD
ChrisBD

Reputation: 9209

If I understand correctly, you're trying to get what you type into console 1 to appear in console 2. Or at least to get the same data to appear in both console windows as sent by telnet commands from another console window.

If this is the case and you're using the same code to setup your command consoles then this won't work locally due to port clashes. The first command console doesn't reliquish ownership of port 21 for the second console to use.

On a windows machine it is now possible to implement port sharing using some WCF functionality. See here for more information.

It is normally advisable to use port numbers that aren't close to any other program when writing your own application. Say 17657 instead of 21, but this may be coloured by what your application intends to do.

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33252

Try to add a Console.ReadLine(); after StartAccept(); to keep the console running.

Upvotes: 1

Related Questions