Esempio n. 1
0
 protected override void CloseNative()
 {
     if (socket != null)
     {
         socket.Close();
         socket = null;
     }
 }
Esempio n. 2
0
        protected override bool ConnectNative(string ip, int port)
        {
            if (socket == null)
            {
                socket = new Java.Net.Socket(ip, port);
            }

            return(true);
        }
        protected override void OnHandleIntent(Intent intent)
        {
            var context = ApplicationContext;
            if (intent.Action.Equals(ActionSendFile))
            {
                var fileUri = intent.GetStringExtra(ExtrasFilePath);
                var host = intent.GetStringExtra(ExtrasGroupOwnerAddress);
                var port = intent.GetIntExtra(ExtrasGroupOwnerPort, 8988);
                var socket = new Socket();

                try
                {
                    Log.Debug(WiFiDirectActivity.Tag, "Opening client socket - ");
                    socket.Bind(null);
                    socket.Connect(new InetSocketAddress(host, port), SocketTimeout);

                    Log.Debug(WiFiDirectActivity.Tag, "Client socket - " + socket.IsConnected);
                    var stream = socket.OutputStream;
                    var cr = context.ContentResolver;
                    Stream inputStream = null;
                    try
                    {
                        inputStream = cr.OpenInputStream(Android.Net.Uri.Parse(fileUri));
                    }
                    catch (FileNotFoundException e)
                    {
                        Log.Debug(WiFiDirectActivity.Tag, e.ToString());
                    }
                    DeviceDetailFragment.CopyFile(inputStream, stream);
                    Log.Debug(WiFiDirectActivity.Tag, "Client: Data written");
                }
                catch (IOException e)
                {
                    Log.Debug(WiFiDirectActivity.Tag, e.Message);
                }
                finally
                {
                    if (socket != null)
                    {
                        if (socket.IsConnected)
                        {
                            try
                            {
                                socket.Close();
                            }
                            catch (IOException e)
                            {
                                // Give up
                                Log.Debug(WiFiDirectActivity.Tag, "Gave up on closing socket " + e.StackTrace);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 4
0
        public void Connect(int sendTimeout = -1, int receiveTimeout = -1)
        {
            SSLSocket sslSocket = null;
            var f = SSLSocketFactory.Default as SSLSocketFactory;
            sslSocket = f.CreateSocket(_remoteHostName, _remotePort) as SSLSocket;
            _socket = sslSocket;

            _socket.SoTimeout = receiveTimeout == -1 ? 0 : receiveTimeout;

            sslSocket.StartHandshake();

            _socket.SoTimeout = 0;
        }
Esempio n. 5
0
        public void Connect(int sendTimeout = -1, int receiveTimeout = -1)
        {
            SSLSocket sslSocket = null;
            var       f         = SSLSocketFactory.Default as SSLSocketFactory;

            sslSocket = f.CreateSocket(_remoteHostName, _remotePort) as SSLSocket;
            _socket   = sslSocket;

            _socket.SoTimeout = receiveTimeout == -1 ? 0 : receiveTimeout;

            sslSocket.StartHandshake();

            _socket.SoTimeout = 0;
        }
 public static bool isOnline()
 {
     try
     {
         int    timeoutMs = 3000;
         Socket sock      = new Socket();
         Java.Net.SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
         sock.Connect(sockaddr, timeoutMs);
         sock.Close();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
    /// <summary> 
    /// Tests if a remote host name is reachable 
    /// </summary>
    /// <param name="host">Host name can be a remote IP or URL of website (no http:// or www.)</param>
    /// <param name="port">Port to attempt to check is reachable.</param>
    /// <param name="msTimeout">Timeout in milliseconds.</param>
    /// <returns></returns>
    public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000)
    {

      if (string.IsNullOrEmpty(host))
        throw new ArgumentNullException("host");

      if (!IsConnected)
        return false;

      host = host.Replace("http://www.", string.Empty).
        Replace("http://", string.Empty).
        Replace("https://www.", string.Empty).
        Replace("https://", string.Empty);

      return await Task.Run(async () =>
      {
        try
        {
          var sockaddr = new InetSocketAddress(host, port);
          using (var sock = new Socket())
          {
          
              await sock.ConnectAsync(sockaddr, msTimeout);
              return true;
      
          }
        }
        catch (Exception ex)
        {
          Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
          return false;
        }
      });
    }
Esempio n. 8
0
 public override Socket CreateSocket(Socket socket, string host, int port, bool autoClose)
 {
     return sslContext.SocketFactory.CreateSocket(socket, host, port, autoClose);
 }
Esempio n. 9
0
 private bool Connect(string serverAddress, int portNumber)
 {
     try {
         Socket s = new Socket(serverAddress, portNumber);
         s.KeepAlive = true;
         writer = new BufferedWriter(new OutputStreamWriter(s.OutputStream));
         reader = new BufferedReader(new InputStreamReader(s.InputStream));
         new ReceivingThread(this).Start();
         new KeepAliveThread(this).Start();
         return true;
     } catch(Exception e) {
         System.Diagnostics.Debug.WriteLine("Failed to connect to TCP server. Error: " + e.GetBaseException().Message);
         return false;
     }
 }
Esempio n. 10
0
 private void Close()
 {
     if(mSocket != null) {
         writer.Flush();
         reader.Reset();
         writer.Close();
         reader.Close();
         mSocket.Close();
         mSocket = null;
     }
 }
 public async Task<bool> IsPortReachable(string host, int port = 80, int msTimeout = 5000)
 {
     return await Task.Run(async () =>
         {
             var sockaddr = new InetSocketAddress(host, port);
             using (var sock = new Socket())
             {
                 try
                 {
                     await sock.ConnectAsync(sockaddr, msTimeout);
                     return true;
                 }
                 catch (Exception)
                 {
                     return false;
                 }
             }
         });
 }
Esempio n. 12
0
        public async Task <string> ClientConnect()
        {
            Java.Net.Socket connection = null;
            BufferedReader  reader     = null;


            try
            {
                // サーバーへ接続
                connection = await Task.Run(() => new Java.Net.Socket("pop.mail.yahoo.co.jp", 110));

                // メッセージ取得オブジェクトのインスタンス化
                reader = new BufferedReader(new InputStreamReader(connection.InputStream));

                // サーバーからのメッセージを受信
                message = await Task.Run(() => reader.ReadLine());



                // 接続確認
                if (message == "")
                {
                    //tv.SetText("サーバーとの接続に失敗しました:" + message, TextView.BufferType.Spannable);
                    //Toast.MakeText(this, "サーバーとの接続に失敗しました。", ToastLength.Long).Show();
                    return("サーバーとの接続に失敗しました。");
                }
                else
                {
                    //tv.SetText("サーバーからのメッセージ:" + message, TextView.BufferType.Spannable);
                    //Toast.MakeText(this, "サーバーとの接続に成功しました。", ToastLength.Long).Show();
                    return("サーバーとの接続に成功しました。");
                    //return this.ClientConnect().Result;
                }
            }
            catch (UnknownHostException e)
            {
                e.PrintStackTrace();
                //tv.SetText("エラー内容:" + e.ToString(), TextView.BufferType.Spannable);
                //Toast.MakeText(this, "サーバーとの接続に失敗しました。", ToastLength.Long).Show();
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
                //tv.SetText("エラー内容:" + e.ToString(), TextView.BufferType.Spannable);
                //Toast.MakeText(this, "サーバーとの接続に失敗しました。", ToastLength.Short).Show();
            }
            finally
            {
                try
                {
                    // 接続終了処理
                    reader.Close();
                    connection.Close();
                }
                catch (IOException e)
                {
                    e.PrintStackTrace();
                    //tv.SetText("エラー内容:" + e.ToString(), TextView.BufferType.Spannable);
                    //Toast.MakeText(this, "サーバーとの接続に失敗しました。", ToastLength.Short).Show();
                }
            }
            return("サーバーとの接続に成功しました。");
        }
        /// <summary> 
        /// Tests if a remote host name is reachable 
        /// </summary>
        /// <param name="host">Host name can be a remote IP or URL of website (no http:// or www.)</param>
        /// <param name="port">Port to attempt to check is reachable.</param>
        /// <param name="msTimeout">Timeout in milliseconds.</param>
        /// <returns></returns>
        public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000)
        {

            if (string.IsNullOrEmpty(host))
                throw new ArgumentNullException("host");

            if (!IsConnected)
                return false;

            host = host.Replace("http://www.", string.Empty).
              Replace("http://", string.Empty).
              Replace("https://www.", string.Empty).
              Replace("https://", string.Empty);

            return await Task.Run(async () =>
            {
                try
                {
                    var tcs = new TaskCompletionSource<InetSocketAddress>();
                    new System.Threading.Thread(async () =>
                    {
                        /* this line can take minutes when on wifi with poor or none internet connectivity
                        and Task.Delay solves it only if this is running on new thread (Task.Run does not help) */
                        InetSocketAddress result = new InetSocketAddress(host, port);

                        if (!tcs.Task.IsCompleted)
                            tcs.TrySetResult(result);

                    }).Start();

                    Task.Run(async () =>
                    {
                        await Task.Delay(msTimeout);

                        if (!tcs.Task.IsCompleted)
                            tcs.TrySetResult(null);
                    });

                    var sockaddr = await tcs.Task;

                    if (sockaddr == null)
                        return false;

                    using (var sock = new Socket())
                    {

                        await sock.ConnectAsync(sockaddr, msTimeout);
                        return true;

                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
                    return false;
                }
            });
        }