0

I am in desperate need of help. I have essentially created a program that (will use) encryption to send messages back and forth. The encryption part is working fine, however I am fairly new to Threads and I can not for the life of me get my Client/Server pieces of the application to line up. The chat program is direct IP connection using TCP, so each host is a client and a server. The issue I appear to be having, when I debug, is that the server thread is either not ready when the Client tries to connect to it, or if it is ready it will not relinquish the Thread so the Client can connect! I have been working on this for hours and it is very frustrating.. I hope someone can help! I've included my code below. This is my code snippet from my MainForm, which constructs the Client and Server aspects:

private void InitializeComponent() {

        server = new ServerSide("127.0.0.1",7865);
        servThread = new Thread(new ThreadStart(server.begin));
        client = new ClientSide("127.0.0.1",7865);
        clientThread = new Thread(new ThreadStart(client.begin));
        servThread.Start();
        clientThread.Start();


        //servThread.Join();
        //clientThread.Join();

}

This is my ServerSide code:

public class ServerSide
{
    String IpString;
    int tcpPort;
    bool goodToGo = false;
    System.Net.IPAddress ipAddress = null;
    public ServerSide(String ip, int tcpPort)
    {
        IpString = ip;
        bool isValidIp = System.Net.IPAddress.TryParse(IpString, out ipAddress);
        if (isValidIp == true) // check if the IP is valid, set the bool to true if so
        {
            goodToGo = true;
        }
        else
        {
            goodToGo = false;
        }
    }

    public void begin()
    {
        try
        {
            IPAddress ipAd = IPAddress.Parse(IpString);

            /* Initializes the Listener */
            TcpListener myList = new TcpListener(ipAd, tcpPort);
            Socket s = null;
            /* Start Listening at the specified port */
            while (true)
            {
                myList.Start();

                if (myList.Pending())
                { 
                        s = myList.AcceptSocket();
                         break;
                }

            }

            String toReceive = "";
                    while (true)
                    {
                        byte[] b = new byte[4096];
                        int k = s.Receive(b);
                        for (int i = 0; i < k; i++)
                            toReceive += Convert.ToString((Convert.ToChar(b[i])));

                        // ASCIIEncoding asen = new ASCIIEncoding();

                        var form = MainForm.ActiveForm as MainForm;
                        if (form != null)
                        {
                            form.messageReceived(toReceive);
                        }
                        toReceive = "";
                    }
                }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }
}

}

ClientSide code:

 public class ClientSide
{
    private String IpString;
    private int tcpPort;
    private TcpClient tcpInt;
    private static Stream stm;
    private System.Net.IPAddress ipAddress = null;
    private bool goodToGo = false;

    public ClientSide(String ip, int tcpPort)
    {

        IpString = ip;
        this.tcpPort = tcpPort;

        bool isValidIp = System.Net.IPAddress.TryParse(IpString, out ipAddress);
        if (isValidIp == true)
        {
            goodToGo = true;
        }
        else
        {
            goodToGo = false;
        }
    }

    public void begin()
    {
        try
        {
            tcpInt = new TcpClient();
            // Console.WriteLine("Connecting.....");



            tcpInt.Connect(IpString, tcpPort);
            // use the ipaddress as in the server program

            // Console.WriteLine("Connected");

            // String str = Console.ReadLine();
            stm = tcpInt.GetStream();
        }

        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }


    public void sendMessage(String str)
    {
      //  stm = tcpInt.GetStream();

        ASCIIEncoding asen = new ASCIIEncoding();
        byte[] ba = asen.GetBytes(str);

        stm.Write(ba, 0, ba.Length);

      /**  byte[] bb = new byte[100];
        int k = stm.Read(bb, 0, 100);

        for (int i = 0; i < k; i++)
            Console.Write(Convert.ToChar(bb[i]));*/

    }
}

}

Once again.. what typically happens is my Client receives an error that the host actively refused the connection.. but I do not know how to time them. I am looking for how to have my server listening for TCP Connections, but still manage to go to my other thread to create the TCP Connecion to send the server (I am testing this on localhost currently). Thanks.

1 Answer 1

7

In the constructor of the ServerSide class, you forgot to initialize the tcpPort member. Because you forgot, the server will try to listen to port 0 and the client will try to connect to port 7865, and it will fail.

Try adding this code to the constructor in the ServerSide class.

this.tcpPort = tcpPort;

As for the threads, you might have a problem if the client thread tries to connect before the server thread has started listening. You can use a loop to try to connect a number of times (let's say 10), with a timeout (let's say 1 second) if you don't succeed. This way, you will retry 10 times and give up after that.

1
  • I think I may have accidentally deleted that fairly recently, the for loop was the solution I was looking for! That part seems to be working, thanks!
    – Ramrod
    Apr 18, 2012 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.