Close() public method

public Close ( ) : void
return void
Esempio n. 1
1
		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();
		}
Esempio n. 2
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();
        }
Esempio n. 3
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 "";
 }
Esempio n. 4
0
        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();
            }
        }
Esempio n. 5
0
        public async Task <bool> SendData()
        {
            bool ret = false;

            try
            {
                await clientSocket.ConnectAsync("127.0.0.1", 38300);

                ret = clientSocket.Connected;
            }
            catch (SocketException se)
            {
            }
            catch (ObjectDisposedException odse)
            {
                clientSocket.Close();
                clientSocket = new TcpClient();
                await clientSocket.ConnectAsync("127.0.0.1", 38300);

                ret = clientSocket.Connected;
            }

            if (ret)
            {
                NetworkStream serverStream = clientSocket.GetStream();
                byte[]        inStream     = new byte[clientSocket.ReceiveBufferSize];
                serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);

                List <string> songs = new List <string>();
                songs = Directory.EnumerateFiles(m_filePath, "*.bkN", SearchOption.AllDirectories).ToList();

                for (int i = 0; i < songs.Count; i++)
                {
                    using (var fileStream = new FileStream(songs[i], FileMode.Open, FileAccess.Read))
                    {
                        try
                        {
                            byte[] outStream = StreamToByteArray(fileStream);
                            serverStream.Write(outStream, 0, outStream.Length);
                            serverStream.Flush();
                        }
                        catch (IOException ioe)
                        {
                            serverStream.Dispose();
                            clientSocket.Close();
                            break; //no active android server host running
                        }
                    }
                }

                serverStream.Dispose();
                serverStream.Close();
                clientSocket.Close();
                StartADBCommannds("forward --remove tcp:38300", null, null);
            }


            return(ret);
        }
        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;
        }
Esempio n. 7
0
        public bool Close()
        {
            bool result = false;

            try
            {
                if (thListen != null)
                {
                    thListen.Abort();
                }
                thListen = null;
                if (tcp != null)
                {
                    tcp.Close();
                }
                tcp      = null;
                result   = true;
                isListen = false;
            }
            catch (Exception e)
            {
                All.Class.Error.Add(e);
            }
            return(result);
        }
Esempio n. 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();
            }
        }
Esempio n. 9
0
        public int Close(out string message)
        {
            int errorCode = 0;

            message = "";
            try
            {
                if (_innolasProxy.Connected)
                {
                    _innolasStream.Close();
                    _innolasProxy.Close();
                }
                else
                {
                    message   = "Proxy not connected";
                    errorCode = -1;
                }
            }
            catch (Exception ex)
            {
                message   = "Exception: " + ex.Message;
                errorCode = -2;
            }
            return(errorCode);
        }
Esempio n. 10
0
 public void Cleanup()
 {
     if (Client != null)
     {
         Client.Close();
     }
 }
Esempio n. 11
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;
            }
Esempio n. 12
0
        public bool Disconnect()
        {
            if (_Client != null)
            {
                try
                {
                    if (_Client.Connected)
                    {
                        _Client.GetStream().Close();
                    }

                    //if (_ReadThread != null && _ReadThread.IsAlive)
                    //{
                    //    _ReadThread.Join(new TimeSpan(0, 0, 5));

                    //}
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                _Client.Close();
                _Client = null;
            }
            return(true);
        }
Esempio n. 13
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                m_ShuttingDown = true;

                foreach (SoundProxy sp in m_SoundProxies.Values)
                {
                    sp.Dispose();
                }

                m_SoundProxies.Clear();

                if (null == m_tcpConnection)
                {
                    return;
                }

                if (null == m_tcpStream)
                {
                    m_tcpConnection.Close();
                }
                else
                {
                    lock (m_tcpStream)
                    {
                        m_tcpConnection.Close();
                        m_tcpStream = null;
                    }
                }

                m_tcpConnection = null;
            }
        }
Esempio n. 14
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;
        }
Esempio n. 15
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;
 }
Esempio n. 16
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;
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Disconnect client from server.
        /// </summary>
        public virtual void Disconnect()
        {
            //Gentle close, terminating thread properly
            TerminateThreadsAndTCPStream();

            Connected = false;
            Client.Close();
            Client = new System.Net.Sockets.TcpClient();
        }
Esempio n. 18
0
 public void Start()
 {
     try
     {
         Thread th = new Thread(() =>
         {
             try
             {
                 byte[] bytes = new byte[1024];
                 int recv;
                 string mess;
                 while (start)
                 {
                     if ((recv = ns.Read(bytes, 0, bytes.Length)) == 0)
                     {
                         Console.WriteLine("disconnected");
                         break;
                     }
                     else if ((recv = ns.Read(bytes, 0, bytes.Length)) == 4)
                     {
                         continue;
                     }
                     try
                     {
                         mess = System.Text.Encoding.UTF8.GetString(bytes, 0, recv);
                         if (Receive != null)
                         {
                             Receive(mess);
                         }
                     }
                     catch { }
                 }
                 tcp.Close();
             }
             catch { }
         });
         th.Start();
         Thread th2 = new Thread(() =>
         {
             while (start)
             {
                 byte[] b = System.Text.Encoding.UTF8.GetBytes("ping");
                 ns.Write(b, 0, b.Length);
                 ns.Flush();
                 Thread.Sleep(30 * 1000);
             }
         });
         th2.Start();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         try { tcp.Close(); } catch { }
         Application.Exit();
     }
 }
Esempio n. 19
0
 public void Dispose()
 {
     if (tcpClient != null)
     {
         if (tcpClient.Connected)
         {
             tcpClient.Close();
         }
         tcpClient = null;
     }
 }
Esempio n. 20
0
 public void disconnectFromBot()
 {
     if (clientSocket != null)
     {
         sendData(sendMsgs[0]);
         clientSocket.GetStream().Close();
         clientSocket.Close();
         log.logMsg(log.messages[5], log.alertColor);
     }
     connectedFalse();
 }
Esempio n. 21
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]);
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Connecte le client Tcp au serveur.
        /// </summary>
        public void Connect()
        {
            if (_tcpClient != null && _tcpClient.Connected == true)
            {
                _tcpClient.Close();
                _tcpClient = null;
            }

            _tcpClient = new System.Net.Sockets.TcpClient();
            _tcpClient.BeginConnect(_serverIP, _serverPort, this.OnConnect, this);
        }
Esempio n. 23
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();
 }
Esempio n. 24
0
        private void receivingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (client.Connected)
            {
                try
                {
                    // read from the buffer
                    stream = client.GetStream();
                    i      = stream.Read(readByte, 0, readByte.Length);
                    data   = Encoding.UTF8.GetString(readByte, 0, i);
                    this.txtReceive.Invoke(new MethodInvoker(delegate()
                    {
                        if (data != "['][CLOSE][']\r\n")
                        {
                            // propmt the received message from the buffer
                            txtReceive.AppendText("\nRECEIVED: " + data + "\n");
                        }
                    }));

                    if (data == "['][CLOSE][']\r\n")
                    {
                        // end connection if token acquired
                        break;
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

            // release the resources
            STR.Close();
            STW.Close();
            receivingWorker.CancelAsync();
            client.Close();
            server.Stop();

            // reset button states
            if (InvokeRequired)
            {
                this.stopBtn.Invoke(new MethodInvoker(delegate()
                {
                    stopBtn.Enabled = false;
                }));
                this.startBtn.Invoke(new MethodInvoker(delegate()
                {
                    startBtn.Enabled = true;
                }));
            }
        }
Esempio n. 25
0
 /// <summary>
 /// 关闭监听端口
 /// </summary>
 public void Close()
 {
     if (thListen != null)
     {
         thListen.Abort();
     }
     thListen = null;
     if (tcp != null)
     {
         tcp.Close();
     }
     tcp    = null;
     isOpen = false;
 }
Esempio n. 26
0
        public void FTP_Send(string filename, string recipientIP)
        {
            System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
            tcpClient.Connect(recipientIP, FTPPORTNO);
            int           BufferSize = tcpClient.ReceiveBufferSize;
            NetworkStream nws        = tcpClient.GetStream();
            FileStream    fs;

            fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            byte[] bytesToSend  = new byte[fs.Length];
            int    numBytesRead = fs.Read(bytesToSend, 0, bytesToSend.Length);
            int    totalBytes   = 0;

            for (int i = 0; i <= fs.Length / BufferSize; i++)
            {
                if (fs.Length - (i * BufferSize) > BufferSize)
                {
                    nws.Write(bytesToSend, i * BufferSize, BufferSize);
                    totalBytes += BufferSize;
                }
                else
                {
                    nws.Write(bytesToSend, i * BufferSize, (int)fs.Length - (i * BufferSize));
                    totalBytes += (int)fs.Length - (i * BufferSize);
                }
                ToolStripStatusLabel1.Text = "Sending " + totalBytes + " bytes....";
                Application.DoEvents();
            }
            ToolStripStatusLabel1.Text = "Sending " + totalBytes + " bytes....Done.";
            fs.Close();
            tcpClient.Close();
        }
Esempio n. 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";
        }
Esempio n. 28
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();
            }

        }
    public void StopExchange()
    {
        exchangeStopRequested = true;

#if UNITY_EDITOR
        if (exchangeThread != null)
        {
            exchangeThread.Abort();
            stream.Close();
            client.Close();
            writer.Close();
            reader.Close();

            stream         = null;
            exchangeThread = null;
        }
#else
        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            socket.Dispose();
            writer.Dispose();
            reader.Dispose();

            socket       = null;
            exchangeTask = null;
        }
#endif
        writer = null;
        reader = null;
    }
Esempio n. 30
0
        public void Dispose()
        {
            if (TokenSource != null)
            {
                if (!TokenSource.IsCancellationRequested)
                {
                    TokenSource.Cancel();
                    TokenSource.Dispose();
                }
            }

            if (_SslStream != null)
            {
                _SslStream.Close();
            }

            if (_NetworkStream != null)
            {
                _NetworkStream.Close();
            }

            if (_TcpClient != null)
            {
                _TcpClient.Close();
                _TcpClient.Dispose();
            }
        }
Esempio n. 31
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;
            }
        }
Esempio n. 32
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();
            }
        }
Esempio n. 33
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;
            }
        }
Esempio n. 34
0
        public void SendMessageToActor()
        {
            int             total = 0;
            EventWaitHandle wait  = new AutoResetEvent(false);

            Actor actor = new LambdaActor(c => { total += (int)c; wait.Set(); });

            ActorSystem system = new ActorSystem();
            var         server = new TcpServer("localhost", 3000, system);

            var result = system.ActorOf(actor, "myactor");
            var path   = result.Path.ToString();

            server.Start();

            var client = new System.Net.Sockets.TcpClient();

            client.Connect("localhost", 3000);
            var channel = new OutputChannel(new System.IO.BinaryWriter(client.GetStream()));

            channel.Write(path);
            channel.Write(1);

            wait.WaitOne();

            Assert.AreEqual(1, total);

            client.Close();
            server.Stop();
            system.Shutdown();
        }
Esempio n. 35
0
    public static bool IsPortOpen(string host, int port, int timeout = 2000, int retry = 1)
    {
        var retryCount = 0;

        while (retryCount < retry)
        {
            // Logical delay without blocking the current thread.
            if (retryCount > 0)
            {
                System.Threading.Tasks.Task.Delay(timeout).Wait();
            }
            var client = new System.Net.Sockets.TcpClient();
            try
            {
                var result  = client.BeginConnect(host, port, null, null);
                var success = result.AsyncWaitHandle.WaitOne(timeout);
                if (success)
                {
                    client.EndConnect(result);
                    return(true);
                }
            }
            catch
            {
                // ignored
            }
            finally
            {
                client.Close();
                retryCount++;
            }
        }
        return(false);
    }
        /// <summary>
        ///
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <param name="serverName">The server name must match the name on the server certificate.</param>
        /// <param name="encryptionPolicy"></param>
        public EncryptedTcpClientNetworkExchangeInterface(System.Net.Sockets.TcpClient tcpClient, string serverName, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocationEncryptionPolicy, EncryptionPolicy encryptionPolicy, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback)
        {
            TcpClient = tcpClient;

            _sslStream = new SslStream(
                TcpClient.GetStream(),
                true,
                userCertificateValidationCallback,
                userCertificateSelectionCallback,
                encryptionPolicy
                );

            // The server name must match the name on the server certificate.
            try
            {
                _sslStream.AuthenticateAsClient(serverName, clientCertificates, enabledSslProtocols, checkCertificateRevocationEncryptionPolicy);
            }
            catch (Exception ex)
            {
                OnErrorEvent(ex);
                TcpClient.Close();
                throw;
            }

            _netStream = TcpClient.GetStream();

            LocalEndPoint  = (IPEndPoint)TcpClient.Client.LocalEndPoint;
            RemoteEndPoint = (IPEndPoint)TcpClient.Client.RemoteEndPoint;

            IsConnected = true;
        }
Esempio n. 37
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("@CONNECTION@OK@");
            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

        }
Esempio n. 38
0
        public static byte[] SendMessage(byte[] messageBytes)
        {
            const int bytesize = 1024 * 1024;

            try                                                                                            // Try connecting and send the message bytes
            {
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient("127.0.0.1", 1234); // Create a new connection
                NetworkStream stream = client.GetStream();

                stream.Write(messageBytes, 0, messageBytes.Length); // Write the bytes
                Console.WriteLine("================================");
                Console.WriteLine("=   Connected to the server    =");
                Console.WriteLine("================================");
                Console.WriteLine("Waiting for response...");

                messageBytes = new byte[bytesize]; // Clear the message

                // Receive the stream of bytes
                Int32 bytes = stream.Read(messageBytes, 0, messageBytes.Length);
                HandleResponse(ref messageBytes, bytes);

                // Clean up
                stream.Dispose();
                client.Close();
            }
            catch (SocketException e) // Catch exceptions
            {
                Console.WriteLine(e.Message);
            }

            return(messageBytes); // Return response
        }
Esempio n. 39
0
        public static List <T> sendMsg <T>(string textToSend)
        {
            //---create a TCPClient object at the IP and port no.---
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(SERVER_IP, PORT_NO);
            NetworkStream nwStream = client.GetStream();

            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

            //---send the text---
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int    bytesRead   = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);

            returnString = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);

            if (returnString == "null")
            {
                return(new List <T>());
            }

            client.Close();

            return(JsonConvert.DeserializeObject <List <T> >(returnString));
        }
Esempio n. 40
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!");            
        }
Esempio n. 41
0
 public void Stop()
 {
     if (tcp != null)
     {
         tcp.Close();
     }
 }
Esempio n. 42
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();
            }
        }
Esempio n. 43
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;
            }
        }
Esempio n. 44
0
 private ClientEntity TryFilter(System.Net.Sockets.TcpClient client)
 {
     try
     {
         client.SendTimeout = SendTimeOutMS;
         RLib.WatchLog.Loger.Log("收到TcpClient", client.Client.RemoteEndPoint.ToString());
         var         stream = client.GetStream();
         List <byte> bs     = new List <byte>();
         stream.ReadTimeout = 1000 * 6;
         //接收第一行数据
         byte[] tmpread = new byte[512];
         int    i       = stream.Read(tmpread, 0, tmpread.Length);
         if (i != -1)
         {
             bs.AddRange(tmpread.Take(i));
             while (stream.DataAvailable)
             {
                 i = stream.Read(tmpread, 0, tmpread.Length);
                 if (i == -1)
                 {
                     break;
                 }
                 bs.AddRange(tmpread.Take(i));
             }
         }
         var stringv = (System.Text.Encoding.UTF8.GetString(bs.ToArray()).Split(new char[] { '\n' }, 1).FirstOrDefault() ?? "").Trim();
         var vhost   = stringv.Split(":".ToArray(), 3);
         if (vhost.Length >= 2)
         {
             float version = 0f;
             if (vhost[0].LastIndexOf('[') > 0 && vhost[0].LastIndexOf(']') == vhost[0].Length - 1)
             {
                 string sversion = vhost[0].Substring(vhost[0].LastIndexOf('[')).TrimStart('[').TrimEnd(']');
                 version  = RLib.Utils.Converter.StrToFloat(sversion);
                 vhost[0] = vhost[0].Substring(0, vhost[0].LastIndexOf('['));
             }
             var tops = vhost[1].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
             var name = vhost.Length == 3 ? vhost[2] : "[null]";
             if (tops.Length > 0)
             {
                 RLib.WatchLog.Loger.Log("收到一个监听者 v=" + version + " name=" + name, "当前连接数" + clients.Count);
             }
             var item = new ClientEntity()
             {
                 Version = version, Client = client, Stream = stream, Topics = tops
             };
             RLib.WatchLog.Loger.Log("收到一个发送者 v=" + version + " name=" + name, "当前连接数" + clients.Count);
             var respyes = Encoding.UTF8.GetBytes("yes\n");
             stream.Write(respyes, 0, respyes.Length);
             stream.Flush();
             return(item);
         }
         else
         {
             client.Close();
         }
     }
     catch (Exception ex) { }
     return(null);
 }
Esempio n. 45
0
        private string IsOnline()
        {
            TcpClient tcpChecker = new TcpClient();
            try
            {
                tcpChecker.Connect(_serverIP, _port);

                tcpChecker.Close();
                return "Online";
            }
            catch
            {
                tcpChecker.Close();
                return "Offline";
            }
        }
Esempio n. 46
0
        //Function that starts connection to server
        //Uses ip address in the ip text box
        public void StartClient(Object sender, EventArgs e)
        {
            //Connect to server
            Messages.Text += "Chat Client Started ....\n";
            clientSocket.Connect(Ip.Text, 8000);
            serverStream = clientSocket.GetStream();

            //Send identifying message to server
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(GetLocalIPAddress() + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            //Listen to messages from server on different thread
            ThreadStart listen = delegate()
            {
                while (!interrupt)
                {
                    byte[] inStream = new byte[10025];
                    serverStream.Read(inStream, 0, inStream.Length);
                    this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
                    {
                        Console.WriteLine(System.Text.Encoding.ASCII.GetString(inStream));
                        Messages.Text += Encoding.ASCII.GetString(inStream).Substring(0, Encoding.ASCII.GetString(inStream).IndexOf("$")) + "\n";
                    }));
                    Thread.Sleep(1000);
                }
                clientSocket.Close();
                Console.WriteLine("exit");
                Console.ReadLine();
            };

            new Thread(listen).Start();
        }
        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;
            }
        }
 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 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();
		}
Esempio n. 50
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];

            }
        }
Esempio n. 51
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;
     }
 }
Esempio n. 52
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;
				}
			}
		}
Esempio n. 53
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;
        }
Esempio n. 54
0
 public void Send(PacketWriter <TOpcode> packet)
 {
     if (client.Connected)
     {
         try
         {
             byte[] data = packet.ToBytes();
             client.GetStream().Write(data, 0, data.Length);
         }
         catch (IOException)
         {
             logger.Error($"Error writing to socket to {Host}:{Port}");
             client.Close();
         }
     }
 }
Esempio n. 55
0
        public IPAddress[] GetAccessibleIPs()
        {
            NetworkInterface[]      networkInterfaces = GetNetworkInterfaces();
            List <NetworkInterface> upInterfaces      = new List <NetworkInterface>();

            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                bool isUp = networkInterface.OperationalStatus == OperationalStatus.Up;
                if (isUp)
                {
                    upInterfaces.Add(networkInterface);
                }
            }

            List <NetworkInterface> externalInterfaces = new List <NetworkInterface>();

            foreach (NetworkInterface networkInterface in upInterfaces)
            {
                IPInterfaceProperties iPInterfaceProperties = networkInterface.GetIPProperties();
                bool isAvailable = false;
                foreach (GatewayIPAddressInformation iPAddressInfo in iPInterfaceProperties.GatewayAddresses)
                {
                    try
                    {
                        if (new Ping().Send(iPAddressInfo.Address).Status == IPStatus.Success)
                        {
                            isAvailable = true;
                            break;
                        }
                    }
                    catch { }
                    try
                    {
                        System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient(iPAddressInfo.Address.ToString(), 80);
                        clnt.Close();
                        isAvailable = true;
                        break;
                    }
                    catch { }
                }
                if (isAvailable)
                {
                    externalInterfaces.Add(networkInterface);
                }
            }

            IPAddress[] iPAddresses;
            iPAddresses = getIPsForInterfaces(externalInterfaces.ToArray(), AddressFamily.InterNetwork);
            if (iPAddresses.Length < 1)
            {
                iPAddresses = getIPsForInterfaces(upInterfaces.ToArray(), AddressFamily.InterNetwork);
            }
            if (iPAddresses.Length < 1)
            {
                iPAddresses = new IPAddress[] { IPAddress.Loopback }
            }
            ;

            return(iPAddresses.ToArray());
        }
Esempio n. 56
0
 private void mDesconectar()
 {
     tEscuchar.Abort();
     clientSocket.Close();
     clientSocket = null;
     //mConectar();
 }
        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;
        }
Esempio n. 58
0
        /// <summary>
        /// 获取当前使用的IP
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            string result = RunApp("route", "print", true);
            Match  m      = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");

            if (m.Success)
            {
                return(m.Groups[2].Value);
            }
            else
            {
                try
                {
                    System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
                    c.Connect("www.baidu.com", 80);
                    string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                    c.Close();
                    return(ip);
                }
                catch (Exception)
                {
                    return(null);
                }
            }
        }
Esempio n. 59
0
        /* Connect socket to boolware server and send LBST to get loadbalancing state.
         * Socket returns YES == boolware is in loadbalancing, NO == Not in loadbalancing.
         * Returns 0 == not in load, 1 == in load
         */
        private int GetValue()
        {
            int val = 404;        // default not in load

            try
            {
                tcpClient = new TcpClient(hostname, BOOLWARE_PORT);
                if (tcpClient.Connected)
                {
                    tcpClient.SendTimeout = 5;
                    NetworkStream ns   = tcpClient.GetStream();
                    byte[]        buff = Encoding.Default.GetBytes("LBST");
                    ns.Write(buff, 0, buff.Length);

                    int    nbytes = ns.Read(buff, 0, 4);
                    String resv   = Encoding.Default.GetString(buff).Substring(0, nbytes);
                    if ("YES".Equals(resv))
                    {
                        val = 200;
                    }
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (tcpClient != null && tcpClient.Connected)
                {
                    tcpClient.Close();
                }
            }

            return(val);
        }
Esempio n. 60
0
        public static void Printer(string bitbmpPath)
        {
            string CRNL    = "\r\n";
            string imgTxt  = get24BitBmpData(bitbmpPath);
            string cmddata = "! 0 200 200 300 1" + CRNL +
                             "EG " + 24 + " " + 50 + " 10 10 " + imgTxt + CRNL +
                             "FORM" + CRNL +
                             "PRINT" + CRNL;

            try
            {
                string ipAddress = "192.168.1.212";
                int    port      = 9100;

                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(ipAddress, port);

                // Write CPCL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
                writer.Write(cmddata);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception)
            {
                // Catch Exception
            }
        }