private void Read(IAsyncResult ar)
        {
            int sizeOfReceivedData = ConnectionSocket.EndReceive(ar);

            if (sizeOfReceivedData > 0)
            {
                OnDataReceived(new DataReceivedEventArgs(sizeOfReceivedData, Decode2(dataBuffer)));
                Send("hi dere!");

                // continue listening for more data
                Listen();
            }
            else // the socket is closed
            {
                if (Disconnected != null)
                {
                    Disconnected(this, EventArgs.Empty);
                }
            }
        }
Exemplo n.º 2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="reintentos"></param>
 protected void Listen(int reintentos)
 {
     if (ConnectionSocket == null)
     {
         return;
     }
     try
     {
         ConnectionSocket.BeginReceive(dataBuffer, 0, dataBuffer.Length, 0, Read, null);
     }
     catch
     {
         if (reintentos < 3)
         {
             Listen(reintentos + 1);
         }
         else
         {
             Dispose();
         }
     }
 }
        protected Result UnbindSocket()
        {
            try
            {
                if (!IsBound)
                {
                    return(Result.Success);
                }

                Result unbind;
                if (!(unbind = CloseConnections()))
                {
                    return(unbind);
                }

                ConnectionSocket.Close(NetworkConfig.CloseConnectionTimeout);
                return(unbind);
            }
            catch (Exception e)
            {
                return(Result.Error(e));
            }
        }
Exemplo n.º 4
0
        void LoopConnect()
        {
            Console.WriteLine("Connecting...");
            int attempts = 0;

            while (!ConnectionSocket.Connected)
            {
                try
                {
                    attempts++;
                    ConnectionSocket.Connect(ServerAddress, Port);
                    connectionLive = true;
                }
                catch (SocketException)
                {
                    Console.Clear();
                    Console.WriteLine("Failed, Connection attempts: " + attempts);
                }
            }

            Console.Clear();
            Console.WriteLine("Connected to " + ServerAddress + ":" + Port);
        }
Exemplo n.º 5
0
        public void SendData(byte[] send)
        {
            var buffer = new byte[send.Length];

            Buffer.BlockCopy(send, 0, buffer, 0, send.Length);

            try
            {
                ConnectionSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, delegate { }, null);
            }
            catch (SocketException)
            {
                Disconnect();
            }
            catch (NullReferenceException)
            {
                Disconnect();
            }
            catch (ObjectDisposedException)
            {
                Disconnect();
            }
        }
Exemplo n.º 6
0
        private int AsyncReceive(out byte[] data, int timeout)
        {
            data = new byte[ReceiveBufferSize];

            IAsyncResult receiveResult = ConnectionSocket.BeginReceive(data, 0, ReceiveBufferSize, SocketFlags.None, null, null);

            bool success = false;

            if (timeout > 0)
            {
                success = receiveResult.AsyncWaitHandle.WaitOne(timeout, true);
            }
            else if (timeout == 0)
            {
                success = receiveResult.AsyncWaitHandle.WaitOne();
            }

            if (!success)
            {
                data = null;
                ConnectionSocket.Dispose();
                return(-1);
            }

            int size = ConnectionSocket.EndReceive(receiveResult);

            if (size > 0)
            {
                TrimData(ref data, size);
            }
            else
            {
                data = null;
            }

            return(size);
        }
Exemplo n.º 7
0
        internal void SendData(byte[] send)
        {
            var buffer = new byte[send.Length];

            Buffer.BlockCopy(send, 0, buffer, 0, send.Length);

            try
            {
                // TODO: Cannot access a disposed object.
                ConnectionSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, delegate { }, null);
            }
            catch (SocketException e)
            {
                var trace = new StackTrace(e, true);
                Log.Print(LogType.Error,
                          $"{e.Message}: {e.Source}" +
                          $"{trace.GetFrame(trace.FrameCount - 1).GetFileName()}:{trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber()}");
                Disconnect();
            }
            catch (NullReferenceException e)
            {
                var trace = new StackTrace(e, true);
                Log.Print(LogType.Error,
                          $"{e.Message}: {e.Source}" +
                          $"{trace.GetFrame(trace.FrameCount - 1).GetFileName()}:{trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber()}");
                Disconnect();
            }
            catch (ObjectDisposedException e)
            {
                var trace = new StackTrace(e, true);
                Log.Print(LogType.Error,
                          $"{e.Message}: {e.Source}" +
                          $"{trace.GetFrame(trace.FrameCount - 1).GetFileName()}:{trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber()}");
                Disconnect();
            }
        }
Exemplo n.º 8
0
 public void HolePunching(EndPoint remoteEndPoint)
 {
     SafeSend(() => ConnectionSocket.SendTo(new byte[0], remoteEndPoint));
     Logger.Log(LogLevel.Detail, "Sent hole punching.");
 }
Exemplo n.º 9
0
 protected override void PreReceiveSettings()
 {
     ConnectionSocket.Bind(Local);
 }
 public void Close()
 {
     Console.WriteLine("WebSocketConnection(): Close()!");
     ConnectionSocket.Close();
 }
Exemplo n.º 11
0
 public void Send(byte[] data, EndPoint remote)
 {
     SafeSend(() => ConnectionSocket.SendTo(Crypto.EncryptData(data), remote));
 }
 private void Listen()
 {
     ConnectionSocket.BeginReceive(dataBuffer, 0, dataBuffer.Length, 0, Read, null);
 }
Exemplo n.º 13
0
 /// <summary>
 /// Close this connection network
 /// </summary>
 public void Disconnect()
 {
     Stream.Close();
     ConnectionSocket.Close();
     LoggedIn = false;
 }
Exemplo n.º 14
0
 // Use this for initialization
 public static void start()
 {
     ConnectionSocket.init();
     ConnectionSocket.test();
 }
Exemplo n.º 15
0
        private void SetupServer()
        {
            Console.WriteLine("\nSetting up server...\n");

            Console.Write("Setting up Hardware Monitor...");
            cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            Console.WriteLine("Done!");

            Console.Write("Setting up Network Communication...");
            ConnectionSocket.Bind(new IPEndPoint(ServerAddress, Port));
            ConnectionSocket.Listen(1);
            ConnectionSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
            Console.WriteLine("Done!");

            Console.WriteLine("\nReady!\n");

            string    consoleInput = "> ";
            Stopwatch timer        = new Stopwatch();

            timer.Start();
            do
            {
                while (!Console.KeyAvailable)
                {
                    if (timer.Elapsed.Seconds > 0)
                    {
                        Time         = Utility.Time();
                        CpuUsage     = (int)Math.Round(cpuCounter.NextValue(), 0);
                        RamAvailable = (int)ramCounter.NextValue();
                        timer.Restart();
                    }

                    Console.SetCursorPosition(0, Console.CursorTop + 2);
                    Console.Write(Utility.EmptyString(Console.BufferWidth - 1));

                    Console.SetCursorPosition(0, Console.CursorTop);
                    Console.Write("Server time: " + Time);
                    string writeLine = "[" + CpuUsage + "% / " + RamAvailable + " RAM]";
                    Console.CursorLeft = Console.BufferWidth - (writeLine.Length + 1);

                    Console.Write(writeLine);
                    Utility.Cleanup();
                    Console.SetCursorPosition(0, Console.CursorTop - 2);

                    Console.CursorLeft = 0;

                    if (consoleInput.Length < Console.BufferWidth)
                    {
                        Console.Write(consoleInput + Utility.EmptyString((Console.BufferWidth - 1) - consoleInput.Length));
                        Console.CursorLeft = consoleInput.Length;
                    }
                    System.Threading.Thread.Sleep(50);
                }
                string key = Console.ReadKey(true).Key.ToString();
                switch (key)
                {
                case "Backspace":
                    if (consoleInput.Length > 2)
                    {
                        consoleInput = consoleInput.Remove(consoleInput.Length - 1);
                    }
                    break;

                case "Spacebar":
                    consoleInput += " ";
                    break;

                case "Enter":
                    Console.CursorTop += 1;
                    Console.CursorLeft = 0;
                    Console.WriteLine("Command: '" + consoleInput.Remove(0, 2) + "' not found");
                    consoleInput = "> ";
                    break;

                default:
                    consoleInput += key.ToLower();
                    break;
                }
            } while (true);
        }
Exemplo n.º 16
0
 /// <summary>
 /// Listens for incoming data
 /// </summary>
 private void Listen() => ConnectionSocket.BeginReceive(_dataBuffer, _dataBufferOffset, _dataBuffer.Length - _dataBufferOffset, 0, Read, null);
Exemplo n.º 17
0
 public void Stop()
 {
     Send("</stream:stream>");
     ConnectionSocket.Shutdown(SocketShutdown.Both);
     ConnectionSocket.Close();
 }
Exemplo n.º 18
0
 protected override void SendSpecialized(byte[] data)
 {
     ConnectionSocket.Send(data);
 }
Exemplo n.º 19
0
 protected override void SendSpecialized(byte[] data)
 {
     ConnectionSocket.Send(CreateHeader(data.Length));
     ConnectionSocket.Send(data);
 }
Exemplo n.º 20
0
 /// <summary>
 /// Close this connection network
 /// </summary>
 public void Disconnect()
 {
     Stream.Close();
     ConnectionSocket.Close();
 }