Exemplo n.º 1
0
        private string TCPHostListen()
        {
            TCPStatus = 0; //Set to listening
            string ReceivedData = "";

            Byte[]    bytes = new Byte[256];
            TcpClient ClientListener;

            if (ComActive == false)
            {
                DebugWrite("In TCPHostListen, ComActive is closed, exiting.");
                TCPStatus = 2;
                return("");
            }


            while (ComActive)
            {
                try
                {
                    DebugWrite("In TCPHostListen, initializing listen setup.");
                    TcpListenerObject.Start();
                    DebugWrite("In TCPHostListen, start sequence OK.");
                }
                catch (SocketException e)
                {
                    TCPStatus = 0; //Set to listening as we will exit the connection now
                    DebugWrite("Error while listening to data as host in TCPHostListen, error: " + e);
                    return("");
                }
                try
                {
                    //TODO
                    ClientListener = TcpListenerObject.AcceptTcpClient();
                    DebugWrite("As host; Client has connected.");
                    ClientListener.ReceiveTimeout = 10000;
                    ClientListener.SendTimeout    = 10000;
                    try
                    {
                        TCPStatus = 1; //Set to connected

                        TcpStreamObject = ClientListener.GetStream();

                        int i;

                        while ((i = TcpStreamObject.Read(bytes, 0, bytes.Length)) != 0 && ComActive)
                        {
                            ReceivedData = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                            DebugWrite("As host; Received data: " + ReceivedData);

                            TCPStatus = 0; //Set to listening as we will exit the connection now
                            ClientListener.Close();
                            return(ReceivedData);
                        }
                    }
                    catch (System.IO.IOException e)
                    {
                        DebugWrite("Error reading data as host in TCPHostListen, error: " + e);
                        SetupCom();
                    }
                }
                catch (System.InvalidOperationException e)
                {
                    DebugWrite("InvalidOperationException in TCPHostListen, error: " + e);
                }
                catch (SocketException e)
                {
                    DebugWrite("SocketException in TCPHostListen, error: " + e);
                }
                catch (Exception e)
                {
                    DebugWrite("Exception in TCPHostListen, error: " + e);
                }
            }

            TCPStatus = 0; //Set to listening as we will exit the connection now
            return("");
        }