Close() public method

public Close ( ) : void
return void
Example #1
1
        /// <summary>
        /// 客户端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="message"></param>
        static void Client(string ip, int port, string message)
        {
            try
            {
                //1.发送数据
                TcpClient client = new TcpClient(ip, port);
                IPEndPoint ipendpoint = client.Client.RemoteEndPoint as IPEndPoint;
                NetworkStream stream = client.GetStream();
                byte[] messages = Encoding.Default.GetBytes(message);
                stream.Write(messages, 0, messages.Length);
                Console.WriteLine("{0:HH:mm:ss}->发送数据(to {1}):{2}", DateTime.Now, ip, message);

                //2.接收状态,长度<1024字节
                byte[] bytes = new Byte[1024];
                string data = string.Empty;
                int length = stream.Read(bytes, 0, bytes.Length);
                if (length > 0)
                {
                    data = Encoding.Default.GetString(bytes, 0, length);
                    Console.WriteLine("{0:HH:mm:ss}->接收数据(from {1}:{2}):{3}", DateTime.Now, ipendpoint.Address, ipendpoint.Port, data);
                }

                //3.关闭对象
                stream.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
            }
            Console.ReadKey();
        }
Example #2
0
 /// <summary>
 /// Attempts to gets data from the other computer in a LAN game
 /// </summary>
 /// <param name="Client">The specified other computer</param>
 /// <returns>The string representing the data recieved, or a blank string if the other computer disconnected</returns>
 public static string GetData(TcpClient Client)
 {
     NetworkStream tStream = Client.GetStream();
     if (tStream.CanRead && Client.Connected)
     {
         Byte[] recievedBytes = new byte[buffersize];
         try
         {
             tStream.Read(recievedBytes, 0, buffersize);
         }
         catch (Exception ex)
         {
             Game.PauseGame("Opponent has disconnected, press ESC to return to main menu.");
             Client.Close();
             return "";
         }
         int culSize = 0;
         for (int i = 0; i < bytestotellsize; i++)
             culSize += recievedBytes[i];
         Byte[] inp = new byte[culSize];
         Array.ConstrainedCopy(recievedBytes, bytestotellsize, inp, 0, culSize);
         return System.Text.Encoding.ASCII.GetString(inp);
     }
     Game.PauseGame("Opponent has disconnected, press ESC to return to main menu.");
     Client.Close();
     return "";
 }
        static void PrimaryProcess(int initval = 0)
        {
            int i = initval;
            Console.WriteLine("I am primary!");
            Process.Start("TCPProcessPair.exe", string.Format("{0} -backup", port));

            TcpClient client = null;
            try
            {
                client = new TcpClient("localhost", port);
                Stream s = client.GetStream();
                StreamWriter sw = new StreamWriter(s);
                sw.AutoFlush = true;
                for (i = initval; true; ++i)
                {
                    Console.WriteLine(i);
                    sw.WriteLine(i);
                    Thread.Sleep(1000);
                }
            }
            catch (IOException)
            {
                if (client != null) client.Close();
                Console.WriteLine("Wanna continue? yes/no");
                string answer = Console.ReadLine();
                if (answer.Equals("yes"))       // without 'if' the process is infinite,
                    PrimaryProcess(i + 1);      // whether primary or backup are killed
            }
            finally
            {
                if (client != null) client.Close();
            }
        }
        public NetworkStream connect_sync()
        {
            try
            {
                ConnectionStatistics.numberOfConnections++;
                //Establish a connection to the node
                channel = new TcpClient();
                channel.Connect(node.GetEndPoint());

                //Get a stream to the node
                stream = channel.GetStream();
                ConnectionStatistics.numberOfConnections++;

                if(stream == null)
                {
                    ConnectionStatistics.missedConnections++;
                    channel.Close();
                    return null;
                }

                if(!stream.CanRead || !stream.CanWrite)
                {
                    ConnectionStatistics.noReadWritePermissions++;
                    stream.Close();
                    channel.Close();
                    return null;
                }
            }
            catch
            {
                return null;
            }
            return stream;
        }
Example #5
0
 public static ServerStatus DoPing(IPEndPoint endPoint, string hostname = null)
 {
     var client = new TcpClient();
     client.Connect(endPoint);
     var manager = new NetworkManager(client.GetStream());
     manager.WritePacket(new HandshakePacket(
         NetworkManager.ProtocolVersion,
         hostname ?? endPoint.Address.ToString(),
         (ushort)endPoint.Port,
         NetworkMode.Status), PacketDirection.Serverbound);
     manager.WritePacket(new StatusRequestPacket(), PacketDirection.Serverbound);
     var _response = manager.ReadPacket(PacketDirection.Clientbound);
     if (!(_response is StatusResponsePacket))
     {
         client.Close();
         throw new InvalidOperationException("Server returned invalid ping response");
     }
     var response = (StatusResponsePacket)_response;
     var sent = DateTime.Now;
     manager.WritePacket(new StatusPingPacket(sent.Ticks), PacketDirection.Serverbound);
     var _pong = manager.ReadPacket(PacketDirection.Clientbound);
     if (!(_pong is StatusPingPacket))
     {
         client.Close();
         throw new InvalidOperationException("Server returned invalid ping response");
     }
     client.Close();
     var pong = (StatusPingPacket)_pong;
     var time = new DateTime(pong.Time);
     response.Status.Latency = time - sent;
     return response.Status;
 }
Example #6
0
            public static string RunClient(string serverName,string activation_info,ref string buffer)
            {                                
                TcpClient client = new TcpClient(serverName,443);                
                SslStream sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );
              
                try
                {
                    sslStream.AuthenticateAsClient(serverName);
                }
                catch (AuthenticationException e)
                {   
                    if (e.InnerException != null)
                    {
                    }
                    client.Close();
                    Environment.Exit(-1);
                }

                byte[] messsage = Encoding.UTF8.GetBytes(activation_info + "\n<EOF>");                
                sslStream.Write(messsage);
                sslStream.Flush();               
                string serverMessage = ReadMessage(sslStream);                
                client.Close();                
                buffer = serverMessage;
                return serverMessage;
            }
Example #7
0
        public static bool ConnValidate(String host, int port, int timeoutMSec)
        {
            bool ret = false;
            timeoutObject.Reset();
            socketException = null;

            TcpClient tcpClient = new TcpClient();
            tcpClient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpClient);

            if (timeoutObject.WaitOne(timeoutMSec, false))
            {
                if (IsConnectionSuccessful)
                {
                    ret = true;
                    tcpClient.Close();
                }
                else
                {
                    //throw socketException;
                }
            }
            else
            {
                //throw new TimeoutException();
            }
            tcpClient.Close();

            return ret;
        }
Example #8
0
        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

                // Read a message from the client
                string input = readMessage(stream);
                Console.WriteLine("Received: {0}", input);

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
Example #9
0
        /// <summary>
        /// msg发送的内容
        /// </summary>
        /// <param name="msgs"></param>
        /// <returns>true发送成功 flase发送失败</returns>
        public void Sendmessage(String msgs)
        {
//            String responseData = null;
            TcpClient client = null;
            NetworkStream stream = null;
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer 
                // connected to the same address as specified by the server, port
                // combination.
                client = new TcpClient(_address, _uport);

                // Translate the passed message into ASCII and store it as a Byte array.
                Byte[] data = Encoding.ASCII.GetBytes(msgs);

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                stream = client.GetStream();

                // Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length);

                Console.WriteLine("Sent: {0}", msgs);

                // Receive the TcpServer.response.

                // Buffer to store the response bytes.
//                data = new Byte[256];

                // String to store the response ASCII representation.
//                responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes. 
//                Int32 bytes = stream.Read(data, 0, data.Length);
//                responseData = Encoding.ASCII.GetString(data, 0, bytes);
//                Console.WriteLine("Received: {0}", responseData);

                // Close everything.
                stream.Close();
                client.Close();

            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
                stream.Close();
                client.Close();
                throw;
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
                throw;
            }
        }
Example #10
0
        public static byte[] DownloadData(string url, Action<int, int> f, int chunkSize)
        {
            var uri = new Uri(url);
            var ip = Dns.GetHostEntry(uri.DnsSafeHost).AddressList[0];

            using (var s = new TcpClient())
            {
                s.Connect(new IPEndPoint(ip, uri.Port));
                var ns = s.GetStream();
                var sw = new StreamWriter(ns);

                sw.Write("GET {0} HTTP/1.0\r\nHost:{1}\r\n\r\n", uri.PathAndQuery, uri.Host);
                sw.Flush();

                var br = new BinaryReader(ns);
                var contentLength = 0;
                var offset = 0;
                for (; ; )
                {
                    var result = br.ReadLine();
                    var kv = result.Split(new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries);

                    if (result == "")
                    {
                        /* data follows the blank line */

                        if (contentLength > 0)
                        {
                            if (f != null)
                                f(offset, contentLength);

                            var data = new byte[contentLength];
                            while (offset < contentLength)
                            {
                                var thisChunk = Math.Min(contentLength - offset, chunkSize);
                                br.Read(data, offset, thisChunk);
                                offset += thisChunk;
                                if (f != null)
                                    f(offset, contentLength);
                            }
                            s.Close();
                            return data;
                        }
                        else
                        {
                            s.Close();
                            return new byte[] { };
                        }
                    }
                    else if (kv[0] == "Content-Length")
                        contentLength = int.Parse(kv[1]);
                }
            }
        }
Example #11
0
 public void sendMessage(RemoteOverlayMessagingLib.Messages.IOverlayMessage message, String host)
 {
     TcpClient tcpConnection = new TcpClient(host, 11253);
     if (tcpConnection.Connected)
     {
         byte[] body = message.createNetworkMessage();
         byte[] header = RemoteOverlayMessagingLib.MessageEncoder.createMessageHeader(message.getMessageId(), body.Length);
         tcpConnection.Client.Send(header, header.Length, SocketFlags.None);
         tcpConnection.Client.Send(body, body.Length, SocketFlags.None);
         tcpConnection.ReceiveTimeout = 20000;
         byte[] recHeader = new byte[8];
         int index = 0;
         while (index < 8)
         {
             int count = tcpConnection.Client.Receive(recHeader, index, 8 - index, SocketFlags.None);
             index += count;
         }
         Int32 messageId = new Int32();
         Int32 length = new Int32();
         RemoteOverlayMessagingLib.MessageEncoder.decodeMessageHeader(recHeader, ref messageId, ref length);
         if (messageId == RemoteOverlayMessagingLib.Messages.ConfirmMessage.MessageId)
         {
             byte[] recBody = new byte[length];
             index = 0;
             while (index < length)
             {
                 int count = tcpConnection.Client.Receive(recBody, index, length - index, SocketFlags.None);
                 index += count;
             }
             try
             {
                 RemoteOverlayMessagingLib.Messages.ConfirmMessage conf = new RemoteOverlayMessagingLib.Messages.ConfirmMessage(recBody, length);
             }
             catch (Exception)
             {
                 // Did not receive confirmation
                 tcpConnection.Close();
                 throw new Exception("Recieved invalid confirmation data");
             }
         }
         else
         {
             tcpConnection.Close();
             throw new Exception("Recieved invalid confirmation message");
         }
     }
     else
     {
         tcpConnection.Close();
         throw new Exception("Could not connect to server");
     }
     tcpConnection.Close();
 }
Example #12
0
        public static void SendRaw(string hostname, int tunnelPort, System.IO.Stream clientStream)
        {
            System.Net.Sockets.TcpClient tunnelClient = null;
            NetworkStream tunnelStream = null;

            try
            {
                tunnelClient = new System.Net.Sockets.TcpClient(hostname, tunnelPort);

                tunnelStream = tunnelClient.GetStream();

                var tunnelReadBuffer = new byte[BUFFER_SIZE];

                Task sendRelay = Task.Factory.StartNew(() => StreamHelper.CopyTo(clientStream, tunnelStream, BUFFER_SIZE));
                Task receiveRelay = Task.Factory.StartNew(() => StreamHelper.CopyTo(tunnelStream, clientStream, BUFFER_SIZE));

                sendRelay.Start();
                receiveRelay.Start();

                Task.WaitAll(sendRelay, receiveRelay);
            }
            catch
            {
                if (tunnelStream != null)
                {
                    tunnelStream.Close();
                    tunnelStream.Dispose();
                }

                if (tunnelClient != null)
                    tunnelClient.Close();

                throw;
            }
        }
		public void Invoke()
		{
			var uri = this.Target;
			var t = new TcpClient();

			t.Connect(uri.Host, this.Port);

			//var w = new StreamWriter(t.GetStream());

			var w = new StringBuilder();

			w.AppendLine("GET" + " " + uri.PathAndQuery + " HTTP/1.1");
			w.AppendLine("Host: " + uri.Host);
			w.AppendLine("Connection: Close");

			// http://www.botsvsbrowsers.com/
			w.Append(@"User-Agent: jsc
Referer: " + this.Referer + @"
Accept:  */*
Accept-Encoding:  gzip,deflate
Accept-Language:  et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset:  windows-1257,utf-8;q=0.7,*;q=0.3
");
			w.AppendLine();

			var data = Encoding.UTF8.GetBytes(w.ToString());

			t.GetStream().Write(data, 0, data.Length);

			// it will take up to a minute to show up
			t.Close();
		}
Example #14
0
        private void sendButton_Click(object sender, EventArgs e)
        {
            BulletinMessage msg = new BulletinMessage();
            msg.Content = this.messageBox.Text;
            msg.Timestamp = DateTime.Now;

            this.statusLogBox.AppendText("CLIENT: Opening connection" + Environment.NewLine);

            using (TcpClient client = new TcpClient())
            {
                client.Connect(IPAddress.Loopback, 8888);

                using (NetworkStream stream = client.GetStream())
                {
                    this.statusLogBox.AppendText("CLIENT: Got connection; sending message..." + Environment.NewLine);
                    this.statusLogBox.AppendText(msg.ToString() + Environment.NewLine);

                    // send data to server
                    Serializer.SerializeWithLengthPrefix(stream, msg, PrefixStyle.Base128);

                    this.statusLogBox.AppendText("CLIENT: Closing connection" + Environment.NewLine);
                    stream.Close();
                }

                client.Close();
            }
        }
        public void CheckMinecraft()
        {
            if (!NeedToUpdate("minecraft", 30))
                return;

            TcpClient tcp = new TcpClient();
            try
            {
                tcp.SendTimeout = 2000;
                tcp.ReceiveTimeout = 2000;
                tcp.NoDelay = true;
                tcp.Client.ReceiveTimeout = 2000;
                tcp.Client.SendTimeout = 2000;

                var async = tcp.BeginConnect(MinecraftHost, MinecraftPort, null, null);
                DateTime dt = DateTime.Now;
                while ((DateTime.Now - dt).TotalSeconds < 3 && !async.IsCompleted)
                    System.Threading.Thread.Sleep(40);
                if (!async.IsCompleted)
                {
                    try
                    {
                        tcp.Close();
                    }
                    catch { { } }
                    MinecraftOnline = false;
                    return;
                }

                if (!tcp.Connected)
                {
                    log.Fatal("Minecraft server is offline.");
                    MinecraftOnline = false;
                    return;
                }

                var ns = tcp.GetStream();
                var sw = new StreamWriter(ns);
                var sr = new StreamReader(ns);

                ns.WriteByte(0xFE);

                if (ns.ReadByte() != 0xFF)
                    throw new Exception("Invalid data");

                short strlen = BitConverter.ToInt16(ns.ReadBytes(2), 0);
                string strtxt = Encoding.BigEndianUnicode.GetString(ns.ReadBytes(2 * strlen));

                string[] strdat = strtxt.Split('§'); // Description§Players§Slots[§]
                MinecraftOnline = true;
                MinecraftSvrDescription = strdat[0];
                MinecraftCurPlayers = ulong.Parse(strdat[1]);
                MinecraftMaxPlayers = ulong.Parse(strdat[2]);
            }
            catch (Exception n)
            {
                log.Fatal("Minecraft server check error: " + n);
                MinecraftOnline = false;
            }
        }
Example #16
0
        private static void CmdProcess(TcpClient __tcpClient,string[] cmdList,string info)
        {
            byte[] buffer = new byte[1024];
            NetworkStream netStr = __tcpClient.GetStream();

            bool result = true;
            for (int i = 0; i < cmdList.Length; i++)
            {
                try
                {
                    netStr.Write(Encoding.ASCII.GetBytes(cmdList[i]), 0, cmdList[i].Length);
                    Thread.Sleep(250);//不要改延时                                            
                    Array.Clear(buffer, 0, buffer.Length);
                    netStr.Read(buffer, 0, buffer.Length);   
                    string str  = Encoding.ASCII.GetString(buffer);
                    if (!str.Contains("OK") && "AT+MODE=0\r\n" != cmdList[i]){ result = false; break; }
                    //复位后首次连接会绘制图形交互界面,这里不对AT+MODE的结果做判断,不会产生影响。
                }
                catch
                {
                    netStr.Close();
                    __tcpClient.Close();
                    PrintLine("CmdInit failure! Enter Any Key Exit!");
                    Console.ReadLine();
                    return;
                }
            }

            //PrintLine("发送消息:{0}", result ? info+" success!" : info+" failure!");            
        }
Example #17
0
        private string IsOnline()
        {
            TcpClient tcpChecker = new TcpClient();
            try
            {
                tcpChecker.Connect(_serverIP, _port);

                tcpChecker.Close();
                return "Online";
            }
            catch
            {
                tcpChecker.Close();
                return "Offline";
            }
        }
Example #18
0
        static bool ReportError(string log, string stacktrace)
        {
            try
            {

            TcpClient client = new TcpClient();
            //IPAddress addr = IPAddress.Parse("fonline2238.net");
            IPAddress addr = IPAddress.Parse("127.0.0.1");
            client.Connect(addr, 2250);
            NetworkStream stream = client.GetStream();

            IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
            string localip=IPHost.AddressList[0].ToString();

            Byte[] data = System.Text.Encoding.ASCII.GetBytes("edata|||"+localip+"|||"+log+"|||"+stacktrace);
            stream.Write(data, 0, data.Length);

            // Receive the TcpServer.response.
            // Close everything.
            stream.Close();
            client.Close();
              }
            catch (ArgumentNullException) { return false; }
            catch (SocketException) { return false; }
            return true;
        }
Example #19
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 #20
0
        private void handleClient(TcpClient socket)
        {
            String rawData;
            String data;
            NetworkStream ns = socket.GetStream();
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);

            sw.WriteLine("@[email protected]@");
            sw.Flush();

            while (true)
            {
                try
                {
                    // do things
                    rawData = sr.ReadLine();

                    Console.WriteLine("Raw data: " + rawData); // debug
                    data = hexaToString(rawData);
                    Console.WriteLine("String data: " + data); // debug
                }
                catch (Exception err)
                {
                    //Console.WriteLine(err.ToString());
                    break;
                }

            }

            ns.Close();
            socket.Close();
            //  finish

        }
Example #21
0
		void Start()
		{
			Debug.LogFormat("current thread({0}): {1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name);
			try
			{
				tcp = new TcpClient();
				Interlocked.Exchange(ref connectCallback, 0);
				var result = tcp.BeginConnect(host, port, ConnectCallback, this);
				if (result.IsCompleted)
				{
					state = tcp.Connected ? "connected" : "connect failed";
				}
				else
				{
					state = "connecting";
				}
			}
			catch (Exception e)
			{
				state = string.Format("excption: {0}", e.Message);
				if (null != tcp)
				{
					tcp.Close();
					tcp = null;
				}
			}
		}
Example #22
0
        private void startCommLaser()
        {
            int remotePort = 10002;

            String IPAddr = jaguarSetting.LaserRangeIP;
            firstSetupComm = true;
            try
            {
                //clientSocket = new TcpClient(IPAddr, remotePort);
                clientSocketLaser = new TcpClient();
                IAsyncResult results = clientSocketLaser.BeginConnect(IPAddr, remotePort, null, null);
                bool success = results.AsyncWaitHandle.WaitOne(500, true);
                
                if (!success)
                {
                    clientSocketLaser.Close();
                    clientSocketLaser = null;
                    receivingLaser = false;
                    pictureBoxLaser.Image = imageList1.Images[3];
                }
                else
                {
                    receivingLaser = true;
                    threadClientLaser = new Thread(new ThreadStart(HandleClientLaser));
                    threadClientLaser.CurrentCulture = new CultureInfo("en-US");
                    threadClientLaser.Start();
                    pictureBoxLaser.Image = imageList1.Images[2];
                }
            }
            catch
            {
                pictureBoxLaser.Image = imageList1.Images[3];

            }
        }
 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;
     }
 }
Example #24
0
 public bool talk()
 {
     try
     {
         if (null != sendPro)
         {
             TcpClient client = new TcpClient();
             client.Connect(IPAddress.Parse(ClientInfo.confMap.value(strClientConfKey.ServerIP)),
                 int.Parse(ClientInfo.confMap.value(strClientConfKey.ServerPort)));
             NetworkStream ns = client.GetStream();
             IFormatter formatter = new BinaryFormatter();
             formatter.Serialize(ns, sendPro);
             reseivePro = (Protocol)formatter.Deserialize(ns);
             client.Close();
         }
         else
         {
             return false;
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Example #25
0
        private void handleClient(TcpClient socket)
        {
            String rawData;
            String data;
            NetworkStream ns = socket.GetStream();
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);

            while (true)
            {
                // do things
                rawData = sr.ReadLine();

                Console.WriteLine("Raw data: "+ rawData); // debug

                data = hexaToString(rawData);
                Console.WriteLine("String data: "+ data);

                // finish

                ns.Close();
                socket.Close();
            }

        }
Example #26
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 #27
0
        public static string dewCmd(string cmd)
        {
            var data = new byte[1024];
            string stringData;
            TcpClient server;
            try
            {
                server = new TcpClient("127.0.0.1", 2448);
            }
            catch (SocketException)
            {
                return "Is Eldorito Running?";
            }
            var ns = server.GetStream();

            var recv = ns.Read(data, 0, data.Length);
            stringData = Encoding.ASCII.GetString(data, 0, recv);

            ns.Write(Encoding.ASCII.GetBytes(cmd), 0, cmd.Length);
            ns.Flush();

            ns.Close();
            server.Close();
            return "Done";
        }
Example #28
0
		public void WorkerProcessMain(string argument, string passwordBase64)
		{
			int port = int.Parse(argument, CultureInfo.InvariantCulture);
			
			client = new TcpClient();
			client.Connect(new IPEndPoint(IPAddress.Loopback, port));
			Stream stream = client.GetStream();
			receiver = new PacketReceiver();
			sender = new PacketSender(stream);
			shutdownEvent = new ManualResetEvent(false);
			receiver.ConnectionLost += OnConnectionLost;
			receiver.PacketReceived += OnPacketReceived;
			sender.WriteFailed += OnConnectionLost;
			
			// send password
			sender.Send(Convert.FromBase64String(passwordBase64));
			
			receiver.StartReceive(stream);
			while (!shutdownEvent.WaitOne(SendKeepAliveInterval, false)) {
				Program.Log("Sending keep-alive packet");
				sender.Send(new byte[0]);
			}
			
			Program.Log("Closing client (end of WorkerProcessMain)");
			client.Close();
			shutdownEvent.Close();
		}
        public TestResultBase Test(Options o)
        {
            var p = new Uri(o.Url);

            var res = new GenericTestResult
            {
                ShortDescription = "TCP connection port " + p.Port,
                Status = TestResult.OK
            };

            try
            {
                var client = new TcpClient();
                client.Connect(p.DnsSafeHost, p.Port);
                res.Status = TestResult.OK;
                client.Close();
            }
            catch (Exception ex)
            {
                res.Status = TestResult.FAIL;
                res.CauseOfFailure = ex.Message;
            }

            return res;
        }
Example #30
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;
            }
        }