Ejemplo n.º 1
0
        /// <summary>
        ///  The OnClick for the "connect"command button.  Create a new client
        ///  socket. Much of this code is exception processing.
        /// </summary>
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            try
            {
                socketClient = new TcpClient(serverName, serverPort);
            }
            catch (Exception err)
            {
                //Console is a sealed object; we can't make it, we can just access
                listBoxOutput.Items.Add("Error in connecting to server.");
                listBoxOutput.Items.Add(err.Message);
                labelStatus.Text      = "Error " + err.Message;
                labelStatus.BackColor = Color.Red;
            }

            if (socketClient == null)
            {
                listBoxOutput.Items.Add("Socket not connected.");
            }
            else
            {
                // Make some streams.  They have rather more
                // capabilities than just a socket.  With this type
                // of socket, we can't read from it and write to it
                // directly.
                connectionStream = socketClient.GetStream();

                inStream  = new BinaryReader(connectionStream);
                outStream = new BinaryWriter(connectionStream);

                listBoxOutput.Items.Add("Socket connected to " + serverName);
                labelStatus.BackColor = Color.Green;
                labelStatus.Text      = "Connected to Server (" + serverName + ")";


                // Disable connect button (we can only connect once) and
                // enable other components.
                buttonConnect.Enabled    = false;
                buttonCarArrived.Enabled = true;


                // We have now accepted a connection:
                //There are several ways to do this next bit. Here I make a
                //network stream and use it to create two other streams, an
                //input and an output stream.   Life gets easier at that
                //point.
                threadConnection = new ThreadConnection(uiContext, socketClient, this);


                // Create a new Thread to manage the connection that receives
                // data.  If you are a Java programmer, this looks like a
                // load of hokum cokum..
                Thread threadRunner = new Thread(new ThreadStart(threadConnection.Run));
                threadRunner.Start();

                Console.WriteLine("Debug: Created new connection class.");
            }
        }