GetStream() public method

public GetStream ( ) : NetworkStream
return NetworkStream
Example #1
1
        public Player(TcpClient client, string ip, byte id)
        {
            try
            {
                this.username = "player";
                this.plyClient = client;
                this.x = 0;
                this.y = 0;
                this.z = 0;
                this.rotx = 0;
                this.roty = 0;
                this.prefix = "";
                this.id = id;
                this.ip = ip;

                this.world = null;

                this.outQueue = new Queue<Packet>();
                this.blockQueue = new Queue<Packet>();
                this.IOThread = new Thread(PlayerIO);
                this.outputWriter = new BinaryWriter(client.GetStream());
                this.inputReader = new BinaryReader(client.GetStream());

                this.IOThread.IsBackground = true;
                this.IOThread.Start();
            }
            catch
            {
            }
        }
Example #2
0
        public StreamingAPIConnect(StreamingListener sl, string ip, int port, LoginResponse lr, bool secure)
        {
            this.sl = sl;
            this.streamingSessionId = lr.StreamingSessionId;
            apiSocket = new System.Net.Sockets.TcpClient(ip, port);
            if (secure)
            {
                SslStream ssl = new SslStream(apiSocket.GetStream());
                ssl.AuthenticateAsClient("xtb.com"); //hardcoded domain, because we use ip-version of the address
                apiWriteStream = new StreamWriter(ssl);
                apiBufferedReader = new StreamReader(ssl);
            }
            else
            {
                NetworkStream ns = apiSocket.GetStream();
                apiWriteStream = new StreamWriter(ns);
                apiBufferedReader = new StreamReader(ns);
            }

            Thread t = new Thread(delegate()
            {
                while (running)
                {
                    readStreamMessage();
                    Thread.Sleep(50);
                }
            });
            t.Start();
            //System.Threading.Timer t = new System.Threading.Timer(o => readStreamMessage(), null, 0, 10);
        }
Example #3
0
        public void TestListen()
        {
            try
            {
                Identd.Start("username");
                Thread.Sleep( 1000 );

                TcpClient client = new TcpClient();
                client.Connect("localhost", 113);

                StreamWriter writer = new StreamWriter( client.GetStream() );
                writer.WriteLine( "a query" );
                writer.Flush();

                StreamReader reader = new StreamReader( client.GetStream() );
                string line = reader.ReadLine();

                Identd.Stop();

                Assertion.AssertEquals( "a query : USERID : UNIX : username", line.Trim() );
            }
            catch( Exception e )
            {
                Assertion.Fail("IO Exception during test:" + e);
            }
        }
Example #4
0
 internal static string OpenConnection()
 {
     errorMsg = string.Empty;
     _dataBuffer = string.Empty;
     int result = 0;
     int.TryParse(ConfigurationSupport.currentPort, out result);
     try
     {
         _client = new TcpClient(ConfigurationSupport.currentHost, result);
         string str = QuickRead(null);
         if (str != ConfigurationSupport.version)
         {
             errorMsg = errorMsg + "Mismatched versions." + Environment.NewLine;
             errorMsg = errorMsg + string.Format("SERVER: ({0})" + Environment.NewLine, str);
             errorMsg = errorMsg + string.Format("CLIENT: ({0})" + Environment.NewLine, ConfigurationSupport.version);
             CloseConnection();
         }
         if (_client.Connected)
         {
             StreamWriter writer = new StreamWriter(_client.GetStream());
             writer.WriteLine(string.Format("VersionInfo {{{0}}}", ConfigurationSupport.version));
             writer.Flush();
             _sslStreamReader = new SslStream(_client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallBack));
             try
             {
                 _sslStreamReader.AuthenticateAsClient(ConfigurationSupport.currentHost, null, SslProtocols.Ssl3, false);
             }
             catch (AuthenticationException exception)
             {
                 errorMsg = errorMsg + "SSL Authentication Error." + Environment.NewLine;
                 errorMsg = errorMsg + exception.ToString();
             }
             _sslStreamWriter = new StreamWriter(_sslStreamReader);
             _sslStreamWriter.AutoFlush = true;
             _sslStreamWriter.WriteLine(string.Format("ValidateUser {0} {1}", ConfigurationSupport.currentUsername, ConfigurationSupport.currentPassword));
             string str2 = QuickRead(_sslStreamReader);
             if (str2 == "UserID INVALID")
             {
                 CloseConnection();
                 errorMsg = "Invalid USERNAME and/or PASSWORD";
             }
             else
             {
                 isConnected = true;
                 ConfigurationSupport.userID = str2.Split(new char[0])[1];
             }
         }
     }
     catch (Exception ex)
     {
         isConnected = false;
         errorMsg = string.Format("Could not connect to {0}:{1}", ConfigurationSupport.currentHost, ConfigurationSupport.currentPort);
     }
     if (isConnected)
     {
         _readBuffer = new byte[0x100];
         _sslStreamReader.BeginRead(_readBuffer, 0, _readBuffer.Length, new AsyncCallback(SguildConnection.OnReceivedData), _client.GetStream());
     }
     return errorMsg;
 }
Example #5
0
        public static string ListFiles()
        {
            using (TcpClient socket = new TcpClient())
            {
                string total = null;
                socket.Connect(IPAddress.Loopback, PORT);

                StreamWriter output = new StreamWriter(socket.GetStream());

                // Send request type line
                output.WriteLine("LIST_FILES");
                // Send message end mark and flush it
                output.WriteLine();
                output.Flush();

                // Read response
                string line;
                StreamReader input = new StreamReader(socket.GetStream());
                while ((line = input.ReadLine()) != null && line != string.Empty)
                    total += line + "/n";

                output.Close();
                socket.Close();
                return total;
            }
        }
Example #6
0
        public Boolean Connect(String ip, int port)
        {
            try
            {
                TcpClient = new System.Net.Sockets.TcpClient();
                TcpClient.ReceiveTimeout = 5000;
                TcpClient.SendTimeout = 5000;
                TcpClient.Connect(ip, port);
                Ns = TcpClient.GetStream();

                Bw = new BinaryWriter(TcpClient.GetStream());
                Br = new BinaryReader(TcpClient.GetStream());

                IsConnected = true;
            }
            catch (Exception e)
            {
                IsConnected = false;
                Log.Cl(e.Message);
                return false;
            }

            ReceptionThread = new Thread(new ThreadStart(Run));
            ReceptionThread.IsBackground = true;
            ReceptionThread.Start();

            return true;
        }
 public TcpConnection(TcpClient socket)
 {
     if (socket == null) throw new ArgumentNullException("socket");
     _socket = socket;
     _inputStream = new StreamReader(socket.GetStream());
     _outputStream = new StreamWriter(socket.GetStream());
 }
Example #8
0
        public void Init(TcpClient tcpclient, int maxPackSize = 2048)
        {
            if (!tcpclient.Connected) throw new Exception("Must be connected");
            _tcpClient = tcpclient;

            base.Init(tcpclient.GetStream(), tcpclient.GetStream(), maxPackSize);
        }
Example #9
0
 static void Main(string[] args)
 {
     TcpClient cl = new TcpClient();
     IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
     cl.Connect(iep);
     Console.WriteLine("Connected to Server!!!");
     //NetworkStream ns = new NetworkStream();
     StreamReader sr = new StreamReader(cl.GetStream());
     StreamWriter sw = new StreamWriter(cl.GetStream());
     string st = sr.ReadLine();
     Console.WriteLine("Server:{0}",st);
     while (true)
     {
         //string st;
         Console.Write("Nhap du lieu gui len Server:");
         st = Console.ReadLine();
         sw.WriteLine(st);
         sw.Flush();
         if (st.ToUpper().Equals("QUIT"))
             break;
         st = sr.ReadLine();
         Console.WriteLine("Data From Server:{0}", st);
     }
     sw.Close();
     sr.Close();
     cl.Close();
     //ns.Close();
 }
        //method: UserConnectionToServer
        //description: initializes a new user connection to the server
        //params: Control owner - owner
        //        string server - server
        //        int port - port
        //        string userName - user's name/username
        //returns: void
        //throws ArgumentException and SocketException and IOException
        public UserConnectionToServer(Control owner, string server, int port, string userName)
        {
            this.owner = owner;

            //get name
            userName = userName.Trim();
            if(userName == "") {
                throw new ArgumentException("Name cannot be blank.", "userName");
            }

            //try to connect
            socket = new TcpClient(server, port);
            reader = new LinePeekableReader(new StreamReader(socket.GetStream()));
            writer = new StreamWriter(socket.GetStream());

            //identify as a user and provide name
            writer.WriteLine("user");
            writer.WriteLine(userName);
            writer.Flush();

            //start reading from server
            Thread thread = new Thread(ConnectionReader);
            thread.IsBackground = true;
            thread.Start();
        }
        public RemoteProcessClient(string host, int port)
        {
            client = new TcpClient(host, port) {SendBufferSize = BufferSizeBytes, ReceiveBufferSize = BufferSizeBytes};

            reader = new BinaryReader(client.GetStream());
            writer = new BinaryWriter(client.GetStream());
        }
Example #12
0
        public override bool Initialize()
        {
            Logger.Log($"Connecting to Twitch IRC -> {Account.Username}");

            _Client = new TcpClient();
            _Client.ConnectAsync("irc.twitch.tv", 6667).Wait();

            _Writer = new StreamWriter(_Client.GetStream());
            _Reader = new StreamReader(_Client.GetStream());

            Logger.Log("Sending login credentials");

            _SendStringRaw($"PASS {Account.OAuth}");
            _SendStringRaw($"NICK {Account.Username}");

            var response = IRCMessage.Parse(_Reader.ReadLine());
            if (response.Type != "001")
            {
                Logger.Log("Server did not return expected login message");
                return false;
            }

            // runners
            new Thread(_SendRunner).Start();
            new Thread(_ReceiveRunner).Start();

            Logger.Log("Connecting to channels");
            foreach (var c in Channels)
                _SendString($"JOIN #{c}", MessagePriority.Medium);

            return true;
        }
 private void ConnectButton_Click(object sender, EventArgs e)
 {
     if ((tcpClient == null) || (!tcpClient.Connected))
     {
         tcpClient = new TcpClient();
         try
         {
             MessageLabel.Text = "Connecting...";
             Application.DoEvents();
             tcpClient.Connect(TransportHostTextBox.Text, (int)TransportPortNumericUpDown.Value);
             streamWriter = new StreamWriter(tcpClient.GetStream());
             streamWriter.AutoFlush = true;
             streamReader = new StreamReader(tcpClient.GetStream());
             backgroundWorker.RunWorkerAsync();
             ConnectButton.Text = "Dis&connect";
             MessageLabel.Text = "Connected";
             TransportHostTextBox.Enabled = false;
             TransportPortNumericUpDown.Enabled = false;
             JabberIDTextBox.Enabled = false;
             Authenticated = false;
             skypeProxy.Command("GET CURRENTUSERHANDLE");
         }
         catch (SocketException ex)
         {
             MessageLabel.Text = ex.Message;
             tcpClient = null;
         }
     }
     else
     {
         backgroundWorker_RunWorkerCompleted(sender, null);
     }
 }
        private static void StopIBController()
        {
            // Stop IBController if it's still running. IBController listens on a port
            // for three commands: STOP, EXIT, and ENABLEAPI. Here we send a STOP, then
            // an EXIT to cleanly shutdown TWS.
            try
            {
                byte[] stop = Encoding.Default.GetBytes("STOP\n");
                byte[] exit = Encoding.Default.GetBytes("EXIT\n");

                // connect to the IBController socket
                TcpClient tcp = new TcpClient(Settings.Default.IBControllerIp, Settings.Default.IBControllerPort);

                // send the "STOP" byte array to the IBController socket
                tcp.GetStream().Write(stop, 0, stop.Length);

                // send the "EXIT" command
                tcp.GetStream().Write(exit, 0, exit.Length);
            }
            catch (SocketException sockEx)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("IBController socket exeception: {0}\n", sockEx.Message);
                builder.AppendLine("Check the IP setting in IBController.ini,");
                builder.AppendLine("ensure it matches the setting in IBControllerService.config.");
                Logger.Instance.WriteError(builder.ToString());

                if (sockEx.InnerException != null)
                    Logger.Instance.WriteError("Inner Exception: {0}", sockEx.InnerException.Message);
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteError(ex.Message);
            }
        }
Example #15
0
        public void Connect(IPEndPoint endPoint, bool secure, bool rogue)
        {
            _connection = new TcpClient();

            _connection.Connect(endPoint);

            if (secure)
            {
                if (rogue)
                {
                    _stream = _connection.GetStream();

                    SendGarbage();
                }
                else
                {
                    var sslStream = new SslStream(_connection.GetStream(), false, (p1, p2, p3, p4) => true);

                    sslStream.AuthenticateAsClient(
                        "localhost",
                        null,
                        SslProtocols.Tls,
                        false
                    );

                    _stream = sslStream;
                }
            }
        }
Example #16
0
		void SendTcpMethod(string[] args)
		{
			//Check for correct amount of arguments
			if (args.Length != 2)
				throw new ArgumentException("Parameters: <Destination> <Port>");

			string server = args[0];
			int servPort = Int32.Parse(args[1]);

			//Create a socket that is connected to a server on a specifed port
			TcpClient client = new TcpClient(server, servPort);
			NetworkStream netStream = client.GetStream();

			//Make an item to quote
			ItemQuote quote = new ItemQuote(12345678909876554L, "5mm Super Widgets", 1000, 1299, true, false);

			//Send text-encoded quote
			ItemQuoteEncoderText coder = new ItemQuoteEncoderText();
			byte[] codedQuote = coder.encode(quote);
			Console.WriteLine("Sening text-encoded quote (" + codedQuote.Length + " bytes): ");
			Console.WriteLine(quote);

			netStream.Write(codedQuote, 0, codedQuote.Length);

			//Receive binary-encoded quote
			ItemQuoteDecoder decoder = new ItemQuoteDecoderBin();
			ItemQuote receivedQuote = decoder.decode(client.GetStream());
			Console.WriteLine("Reveived Binary-Encode Quote:");
			Console.WriteLine(receivedQuote);

		}
Example #17
0
        public ServerConnection(string host, int port, string username, string password)
        {
            Host = host;
            Port = port;
            Username = username;
            _currentConnection = this;

            try
            {
                Client = new TcpClient(host, port);
                Reader = new StreamReader(Client.GetStream());
                Writer = new StreamWriter(Client.GetStream());

                if (password.Equals(""))
                {
                    Writer.WriteLine("M:/name " + username);
                } else
                {
                    Writer.WriteLine("M:/auth " + username + " " + password);
                }
                Writer.Flush();

                Writer.WriteLine("S:Client");
                Writer.Flush();
                Writer.WriteLine("S:Account");
                Writer.Flush();
                Writer.WriteLine("S:ChannelClientList");
                Writer.Flush();
            } catch
            {
                Client = null;
            }
        }
Example #18
0
        public GameClient(TcpClient selfClient, Guid onlineId, IClientKiller killer, ChatManager manager, GameLoop game)
        {
            _self = selfClient;
            _self.NoDelay = true;
            _self.Client.NoDelay = true;
            _reader = new BinaryReader(_self.GetStream());
            _writer = new BinaryWriter(_self.GetStream());
            _clientKiller = killer;
            _game = game;
            ChatManager chatManager = manager;
            chatManager.Join(this);
            _auth = AuthorisationManager.Resolve();

            _packetReader = PacketReader.Resolve<ServerPacketReader>();
            _packetReader.InitialiseMapping();

            OnlineId = onlineId;
            _active = true;

            _subs = new List<PacketSubscriber>
                    {
                        this,
                        _game,
                        chatManager
                    };

            Task.Factory.StartNew(Receive);
        }
Example #19
0
        public Session( World _world, TcpClient _client ) {

            world = _world;
            loginTime = DateTime.Now;

            canReceive = true;
            canQueue = true;
            canSend = false;
            canDispose = false;

            outputQueue = new Queue<Packet>();
            priorityOutputQueue = new Queue<Packet>();
            queueLock = new object();
            priorityQueueLock = new object();

            client = _client;
            client.SendTimeout = 10000;
            client.ReceiveTimeout = 10000;
            
            reader = new BinaryReader( client.GetStream() );
            writer = new PacketWriter( new BinaryWriter( client.GetStream() ) );

            world.log.Log( "Session: {0}", LogType.Debug, ToString() );

            ioThread = new Thread( IoLoop );
            ioThread.IsBackground = true;
            ioThread.Start();
        }
Example #20
0
        private void Connect()
        {
            try
            {
                client = new TcpClient();
                client.Connect("localhost", 1992);

                using (StreamReader reader = new StreamReader(client.GetStream(), Encoding.ASCII))
                {
                    writer = new StreamWriter(client.GetStream(), Encoding.ASCII);
                    connected = true;
                    OnConnected();

                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        OnData(JObject.Parse(line));
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error("Socket", "Thread crashed: " + e.ToString());
                client.Close();
                connected = false;
                OnDisconnected();
                Logger.Verbose("Socket", "Waiting before trying reconnect.");
                Util.RunLater(() => { Connect(); }, "Reconnect", TimeSpan.FromSeconds(30));
            }
        }
 public string GetCompletion(string[] args)
 {
     if (args == null || haxeProcess == null)
         return string.Empty;
     if (!IsRunning()) StartServer();
     try
     {
         var client = new TcpClient("127.0.0.1", port);
         var writer = new StreamWriter(client.GetStream());
         writer.WriteLine("--cwd " + (PluginBase.CurrentProject as HaxeProject).Directory);
         foreach (var arg in args)
             writer.WriteLine(arg);
         writer.Write("\0");
         writer.Flush();
         var reader = new StreamReader(client.GetStream());
         var lines = reader.ReadToEnd();
         client.Close();
         return lines;
     }
     catch(Exception ex)
     {
         TraceManager.AddAsync(ex.Message);
         if (!failure && FallbackNeeded != null)
             FallbackNeeded(false);
         failure = true;
         return string.Empty;
     }
 }
        public async Task HandleClientAsync(TcpClient c)
        {
            string msg = null;
            bool connected = true;

            Console.WriteLine($"Connection accepted {DateTime.Now.ToShortTimeString()}");
            using (var output = new StreamWriter(c.GetStream(), UTF32Encoding.ASCII) { AutoFlush = true })
            {
                using (var input = new StreamReader(c.GetStream(), UTF32Encoding.ASCII))
                {
                    while (connected)
                    {
                        switch (msg = await input.ReadLineAsync())
                        {
                            case "done":
                                connected = false;
                                break;
                            default:
                                await output.WriteLineAsync(msg);
                                break;
                        }
                    }
                }

            }
            c.Close();
            Console.WriteLine("bye...");
        }
Example #23
0
        public string Execute(string command)
        {
            try
            {
                Log.InfoFormat("Executing command {0} @{1}:{2}", command, HostName, Port);

                var client = new TcpClient(HostName, Port);

                var commandBytes = ASCIIEncoding.ASCII.GetBytes(command);

                client.GetStream().Write(commandBytes, 0, commandBytes.Length);

                var buffer = new byte[MAX_BUFFER_LENGTH];

                var readLen = client.GetStream().Read(buffer, 0, buffer.Length);

                var result = ASCIIEncoding.ASCII.GetString(buffer.Take(readLen).ToArray());

                client.Close();

                return result;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
                throw;
            }
        }
Example #24
0
		public string connect()
		{
			//Initialize to the pop server.  This code snipped "borrowed"
			//with some modifications...
			//from the article "Retrieve Mail From a POP3 Server Using C#" at
			//www.codeproject.com by Agus Kurniawan
			//http://www.codeproject.com/csharp/popapp.asp

			// create server with port 110
			Server = new TcpClient(pop,110);								
		
			try
			{
				// initialization
				NetStrm = Server.GetStream();
				RdStrm= new StreamReader(Server.GetStream());

				//The pop session is now in the AUTHORIZATION state
				state=connect_state.AUTHORIZATION ;
				return(RdStrm.ReadLine ());
			}			
			catch(InvalidOperationException err)
			{
				return("Error: "+err.ToString());
			}

		}
Example #25
0
        private static void ListLocations(string fileName)
        {
            using (TcpClient socket = new TcpClient())
            {
                socket.Connect(IPAddress.Loopback, PORT);

                StreamWriter output = new StreamWriter(socket.GetStream());

                // Send request type line
                output.WriteLine("LIST_LOCATIONS");
                // Send message payload
                output.WriteLine(fileName);
                // Send message end mark and flush it
                output.WriteLine();
                output.Flush();

                // Read response
                string line;
                StreamReader input = new StreamReader(socket.GetStream());
                while ((line = input.ReadLine()) != null && line != string.Empty)
                    Console.WriteLine(line);

                output.Close();
                socket.Close();
            }
        }
Example #26
0
        /// <summary>
        /// Retrieves whois information
        /// </summary>
        /// <param name="domainName">The registrar or domain or name server whose whois information to be retrieved</param>
        /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
        /// <returns></returns>
        public static string Lookup(string domainName, RecordType recordType)
        {
            string whoisServerName = WhoisServerResolver.GetWhoisServerName(domainName);
            using (TcpClient whoisClient = new TcpClient())
            {
                whoisClient.Connect(whoisServerName, Whois_Server_Default_PortNumber);

                string domainQuery = recordType.ToString() + " " + domainName + "\r\n";
                byte[] domainQueryBytes = Encoding.ASCII.GetBytes(domainQuery.ToCharArray());

                Stream whoisStream = whoisClient.GetStream();
                whoisStream.Write(domainQueryBytes, 0, domainQueryBytes.Length);

                StreamReader whoisStreamReader = new StreamReader(whoisClient.GetStream(), Encoding.ASCII);

                string streamOutputContent = "";
                List<string> whoisData = new List<string>();
                while (null != (streamOutputContent = whoisStreamReader.ReadLine()))
                {
                    whoisData.Add(streamOutputContent);
                }

                whoisClient.Close();

                return String.Join(Environment.NewLine, whoisData);
            }
        }
Example #27
0
 public Form1()
 {
     InitializeComponent();
     client = new TcpClient("127.0.0.1",8888);
     r = new StreamReader(client.GetStream());
     w = new StreamWriter(client.GetStream());
 }
Example #28
0
        private void SendAsync( )
        {
            TcpClient client = new TcpClient( Peer.EndPoint.AddressFamily );

            try
            {
                client.SendTimeout = 30;
                client.Connect( Peer.EndPoint );

                using ( BinaryReader NetworkInStream = new BinaryReader( client.GetStream( ) ) )
                using ( BinaryWriter NetworkOutStream = new BinaryWriter( client.GetStream( ) ) )
                {
                    bool sendPeers = Peer.ShouldSendPeers;
                    var header = new Header( sendPeers );
                    NetworkOutStream.Write( header.ToString( ) );
                    NetworkOutStream.Flush( );

                    // Update the statistics.
                    Peer.RegisterEvent( PeerStatistics.EventType.SentInfo );
                    if ( sendPeers )
                    {
                        log.InfoFormat( "Sent {0} peers to {1}", PeerList.Peers.Count, Peer );
                        Peer.RegisterEvent( PeerStatistics.EventType.SentPeerList );
                    }
                }
            }
            catch ( SocketException e ) { log.Info( "Error during outgoing who's-there: " + e ); }
            catch ( IOException e ) { log.Info( "Error during outgoing who's-there: " + e ); }
        }
 public void Connect(IPEndPoint remoteAddress)
 {
     BaseSocket = new TcpClient();
     BaseSocket.Connect(remoteAddress);
     OutputStream = new StreamWriter(new BufferedStream(BaseSocket.GetStream()));
     InputStream = new StreamReader(new BufferedStream(BaseSocket.GetStream()));
 }
Example #30
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         endereco_ip = IPAddress.Parse("127.0.0.2");
         servidor = new TcpClient();
         servidor.Connect(endereco_ip, 2502);
         conectado = true;
         enviador = new StreamWriter(servidor.GetStream());
         enviador.WriteLine("3");
         enviador.Flush();
         enviador = new StreamWriter(servidor.GetStream());
         enviador.Write(NomeUsuario);
         enviador.Flush();
         enviador = new StreamWriter(servidor.GetStream());
         enviador.WriteLine(txt_senha.Text);
         enviador.Flush();
         comunicacao = new Thread(new ThreadStart(RespostaServidor));
         comunicacao.Start();
         status.Text = "Conectado";
     }
     catch (Exception erro) {
         MessageBox.Show(erro.Message.ToString(), "Erro", MessageBoxButtons.OK);
     }
 }