Example #1
1
        public TCPSocket(Socket from, bool socket_listening)
        {
            sock = from;
            listening = socket_listening;

            if (socket_listening)
            {
                IPEndPoint tmp = (IPEndPoint)sock.LocalEndPoint;
                port = (ushort)tmp.Port;
                ep = tmp;
            }
            else
            {
                IPEndPoint tmp = (IPEndPoint)sock.RemoteEndPoint;
                port = (ushort)tmp.Port;
                ep = tmp;
            }

            if (sock.Blocking == false)
            {
                sock.Blocking = true;
            }

            sock.ReceiveBufferSize = 1024 * 64; // 64 kb
            sock.SendBufferSize = 1024 * 64; // 64 kb
        }
 public TimeSpan GetRTO(EndPoint ep)
 {
     State state = GetState (ep, InvalidValue);
     if (state == null)
         return _defaultRTO;
     return new TimeSpan (Math.Max (_minRTO, state.RTO) * TimeSpan.TicksPerMillisecond);
 }
        public UDPPacketBuffer()
        {
            this.Data = new byte[BUFFER_SIZE];

            // this will be filled in by the call to udpSocket.BeginReceiveFrom
            RemoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
        }
        protected void Test1(IDatagramEventSocket[] sockets, EndPoint[] endPoints)
        {
            byte[] sendData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
            int recvIdx = -1, recvSize = -1;
            byte[] recvData = null;
            AutoResetEvent done = new AutoResetEvent (false);

            for (int i = 0; i < sockets.Length; i++) {
                sockets[i].Bind (endPoints[i]);
                sockets[i].Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
                    recvIdx = Array.IndexOf<IDatagramEventSocket> (sockets, sender as IDatagramEventSocket);
                    recvSize = e.Size;
                    recvData = (byte[])e.Buffer.Clone ();
                    done.Set ();
                });
            }

            for (int i = 0; i < sockets.Length; i++) {
                for (int k = 0; k < endPoints.Length; k++) {
                    sockets[i].SendTo (sendData, endPoints[k]);
                    done.WaitOne ();
                    Array.Resize<byte> (ref recvData, recvSize);
                    string id = "#" + (i + 1).ToString () + "." + (k + 1).ToString ();
                    Assert.AreEqual (k, recvIdx, id + ".1");
                    Assert.AreEqual (sendData.Length, recvSize, id + ".2");
                    Assert.AreEqual (sendData, recvData, id + ".3");
                }
            }
        }
Example #5
0
        internal NetState(EndPoint ep)
        {
            EndPoint = ep;

            AddClient(this);
            LogLine("Connected");
        }
        public void BeginReceiveAll(byte[] buffer, int count, EndPoint remoteEndPoint)
        {
            ValidateTransferAllArguments(buffer, ref count);

            var transfered = 0;
            AsyncCallback callback = null;
            callback = result =>
            {
                var endPoint = result.AsyncState as EndPoint;
                if (endPoint == null)
                    return;

                var current = Socket.EndReceiveFrom(result, ref endPoint);
                if (current == 0)
                {
                    ReceiveCompleted?.Invoke(this, new TransferEventArgs(this, buffer, transfered, endPoint));
                    return;
                }

                transfered += current;
                if (transfered < current)
                    Socket.BeginReceiveFrom(buffer, transfered, count - transfered, SocketFlags.None, ref endPoint, callback, endPoint);
                else
                    ReceiveCompleted?.Invoke(this, new TransferEventArgs(this, buffer, transfered, endPoint));
            };

            Socket.BeginReceiveFrom(buffer, transfered, count - transfered, SocketFlags.None, ref remoteEndPoint, callback, remoteEndPoint);
        }
Example #7
0
        public EchoConnectionHandler(EndPoint remote, IActorRef connection)
        {
            // we want to know when the connection dies (without using Tcp.ConnectionClosed)
            Context.Watch(connection);

            Receive<Tcp.Received>(received =>
            {
                var text = Encoding.UTF8.GetString(received.Data.ToArray()).Trim();
                Console.WriteLine("Received '{0}' from remote address [{1}]", text, remote);
                if (text == "exit")
                    Context.Stop(Self);
                else
                    Sender.Tell(Tcp.Write.Create(received.Data));
            });
            Receive<Tcp.ConnectionClosed>(closed =>
            {
                Console.WriteLine("Stopped, remote connection [{0}] closed", remote);
                Context.Stop(Self);
            });
            Receive<Terminated>(terminated =>
            {
                Console.WriteLine("Stopped, remote connection [{0}] died", remote);
                Context.Stop(Self);
            });
        }
        public bool HandleFlood(EndPoint id)
        {
            if (_floods.ContainsKey(id))
            {
                FloodCount counter = _floods[id];
                counter.PacketCount++;
                _floods[id] = counter;

                if (counter.StopWatch.ElapsedMilliseconds > _msecTime)
                {
                    _floods.Remove(id);
                }
                else
                {
                    _floods.Remove(id);
                    return false;
                }
            }
            else
            {
                FloodCount counter = new FloodCount();
                counter.PacketCount = 1;
                counter.StopWatch.Start();

                _floods.Add(id, counter);

            }

            return true;
        }
Example #9
0
        private void Connect_Click(object sender, EventArgs e)
        {
            try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(IPClient_1.Text), Convert.ToInt32(PortClient_1.Text));
                sck.Bind(epLocal);

                epRemote = new IPEndPoint(IPAddress.Parse(IPClient_2.Text), Convert.ToInt32(PortClient_2.Text));
                sck.Connect(epRemote);

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

                Connect.Enabled = false;
                Send.Enabled = true;
                Сondition.Text = "Подключено";
                tbSend.Focus();

                form1.Form1_IPClient_1 = IPClient_1.Text; form1.Form1_IPClient_2 = IPClient_2.Text;
                form1.Form1_PortClient_1 = PortClient_1.Text; form1.Form1_PortClient_2 = PortClient_2.Text;
                form1.Player1.Text = NameClient_1.Text; form1.Player2.Text = NameClient_2.Text;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                MessageBox.Show("Проблема с подключением, проверте: \r\n - верно ли внесены сетевые настройки игры;\r\n - отсутствует сетевое подключение;\r\n - Ваш противник покинул игру или неуспел подключится.", "Oшибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
        }
 internal ServerCounters(EndPoint endpoint)
 {
     this.EndPoint = endpoint;
     this.Interactive = new ConnectionCounters(ConnectionType.Interactive);
     this.Subscription = new ConnectionCounters(ConnectionType.Subscription);
     this.Other = new ConnectionCounters(ConnectionType.None);
 }
Example #11
0
        public void Connect(EndPoint endPoint)
        {
            byte[] data = new byte[1024];
            string input, stringData;
            int recv;
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
            Console.WriteLine("Default timeout: {0}", sockopt);
            server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _timeout);
            sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
            Console.WriteLine("New timeout: {0}", sockopt);

            string welcome = "Hello, are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, endPoint);

            data = new byte[1024];
            try
            {
                Console.WriteLine("Waiting from {0}:", endPoint.ToString());
                recv = server.ReceiveFrom(data, ref endPoint);
                Console.WriteLine("Message received from {0}:", endPoint.ToString());
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode == SocketError.HostUnreachable)
                    throw new Exception("CLOSED");
                throw new Exception("TIME_OUT");
            }
            Console.WriteLine("Stopping client");
            server.Close();
        }
 protected override void CreateMessagingSocket(int idx, SymmetricKey key, out IMessagingSocket socket, out EndPoint endPoint)
 {
     endPoint = new IPEndPoint (_adrsGen.Next (), 10000);
     VirtualDatagramEventSocket sock = new VirtualDatagramEventSocket (_net, ((IPEndPoint)endPoint).Address);
     sock.Bind (endPoint);
     socket = new VirtualMessagingSocket (sock, true, _interrupter, DefaultRTO, DefaultRetryCount, 1024, 1024);
 }
Example #13
0
 public void Bind2(EndPoint ep)
 {
     if (ep == null)
         Bind(new IPEndPoint(IPAddress.Any, 0));
     else
         Bind(ep);
 }
	/// <summary>
	/// Constructor.
	/// </summary>
	/// <param name="hostEndPoint">Identifies a Network resource that this server is listening on.</param>
	/// <param name="bufferSize">Size of the buffer to use when receiving data from a connected client.</param>
	/// <param name="clientReadTimeout">amount of time that the server will wait 
	/// for a client to send data before timing the client out.</param>
	/// <param name="clientSendTimeout">amount of time that the server will wait 
	/// for a client to receive data before timing the client out.</param>
	public SocketServer(EndPoint hostEndPoint, int bufferSize, TimeSpan clientReadTimeout, TimeSpan clientSendTimeout)
	{
		_hostEndPoint = hostEndPoint;
		_bufferSize = bufferSize;
		_clientReadTimeout = clientReadTimeout;
		_clientSendTimeout = clientSendTimeout;
	}
        State GetState(EndPoint ep, TimeSpan rtt)
        {
            if (_states == null) {
                lock (this) {
                    if (_state == null && !InvalidValue.Equals (rtt))
                        _state = new State ((int)rtt.TotalMilliseconds, _timerGranularity);
                    return _state;
                }
            }

            IPEndPoint ipep = ep as IPEndPoint;
            if (ipep == null)
                throw new ArgumentException ();

            State state;
            bool success;
            using (_lock.EnterReadLock ()) {
                success = _states.TryGetValue (ipep.Address, out state);
            }
            if (!success && !InvalidValue.Equals (rtt)) {
                using (_lock.EnterWriteLock ()) {
                    if (!_states.TryGetValue (ipep.Address, out state)) {
                        state = new State ((int)rtt.TotalMilliseconds, _timerGranularity);
                        _states.Add (ipep.Address, state);
                    }
                }
            }
            return state;
        }
Example #16
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="endPoint">Specifies endpoint of sender</param>
 /// <param name="msg">Message associated with event</param>
 /// <param name="_packet">Packet received</param>
 /// <param name="exception">Any exception, if occured</param>
 public NetEventArgs(EndPoint endPoint, string msg, NetPacket _packet, Exception exception)
 {
     this._endPoint = endPoint;
     this._msg = msg;
     this._packet = _packet;
     this._exception = exception;
 }
Example #17
0
 Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint)
 {
     var taskSource = new TaskCompletionSource<ActiveConnectResult>();
     var socket = new Socket(targetEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     socket.BeginConnect(targetEndPoint, OnActiveConnectCallback, new ActiveConnectState(taskSource, socket));
     return taskSource.Task;
 }
Example #18
0
        /// <summary>
        /// This code is used to connect to a TCP socket with timeout option.
        /// </summary>
        /// <param name="endPoint">IP endpoint of remote server</param>
        /// <param name="timeoutMs">Timeout to wait until connect</param>
        /// <returns>Socket object connected to server</returns>
        public static Socket ConnectToServerWithTimeout(EndPoint endPoint, int timeoutMs)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Blocking = false;
                socket.Connect(endPoint);
                socket.Blocking = true;
                return socket;
            }
            catch (SocketException socketException)
            {
                if (socketException.ErrorCode != 10035)
                {
                    socket.Close();
                    throw;
                }

                if (!socket.Poll(timeoutMs * 1000, SelectMode.SelectWrite))
                {
                    socket.Close();
                    throw new NGRIDException("The host failed to connect. Timeout occured.");
                }

                socket.Blocking = true;
                return socket;
            }
        }
        public Connect(EndPoint remoteEndPoint)
        {
            if (remoteEndPoint == null)
                throw new ArgumentNullException("remoteEndPoint");

            _remoteEndPoint = remoteEndPoint;
        }
 // static methods
 internal static MongoWaitQueueFullException ForConnectionPool(EndPoint endPoint)
 {
     var message = string.Format(
         "The wait queue for acquiring a connection to server {0} is full.",
         EndPointHelper.ToString(endPoint));
     return new MongoWaitQueueFullException(message);
 }
Example #21
0
        public void beginWrite(EndPoint endpoint, Buffer buf)
        {
            if(!(endpoint is IPEndPoint))
            {
                throw new Ice.FeatureNotSupportedException("SOCKS4 does not support domain names");
            }
            else if(endpoint.AddressFamily != AddressFamily.InterNetwork)
            {
                throw new Ice.FeatureNotSupportedException("SOCKS4 only supports IPv4 addresses");
            }

            //
            // SOCKS connect request
            //
            IPEndPoint addr = (IPEndPoint)endpoint;
            buf.resize(9, false);
            ByteBuffer.ByteOrder order = buf.b.order();
            buf.b.order(ByteBuffer.ByteOrder.BIG_ENDIAN); // Network byte order.
            buf.b.position(0);
            buf.b.put(0x04); // SOCKS version 4.
            buf.b.put(0x01); // Command, establish a TCP/IP stream connection
            buf.b.putShort((short)addr.Port); // Port
            buf.b.put(addr.Address.GetAddressBytes()); // IPv4 address
            buf.b.put(0x00); // User ID.
            buf.b.position(0);
            buf.b.limit(buf.size());
            buf.b.order(order);
        }
Example #22
0
        public XSPWorker(Socket client, EndPoint localEP, ApplicationServer server,
			bool secureConnection,
			Mono.Security.Protocol.Tls.SecurityProtocolType SecurityProtocol,
			X509Certificate cert,
			PrivateKeySelectionCallback keyCB,
			bool allowClientCert,
			bool requireClientCert)
        {
            if (secureConnection) {
                ssl = new SslInformation ();
                ssl.AllowClientCertificate = allowClientCert;
                ssl.RequireClientCertificate = requireClientCert;
                ssl.RawServerCertificate = cert.GetRawCertData ();

                netStream = new LingeringNetworkStream (client, true);
                SslServerStream s = new SslServerStream (netStream, cert, requireClientCert, false);
                s.PrivateKeyCertSelectionDelegate += keyCB;
                s.ClientCertValidationDelegate += new CertificateValidationCallback (ClientCertificateValidation);
                stream = s;
            } else {
                netStream = new LingeringNetworkStream (client, false);
                stream = netStream;
            }

            sock = client;
            this.server = server;
            this.remoteEP = (IPEndPoint) client.RemoteEndPoint;
            this.localEP = (IPEndPoint) localEP;
        }
Example #23
0
        /// <summary>
        /// <see cref="AbstractTcpClient.ConnectInternal"/>
        /// </summary>
        protected override void ConnectInternal(Socket socket, EndPoint endpoint)
        {
            try
            {
                if (Object.ReferenceEquals(socket, null))
                {
                    socket = new Socket(
                        endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                }
                if (Object.ReferenceEquals(connectEventArgs, null))
                {
                    connectEventArgs = new SocketAsyncEventArgs();
                    connectEventArgs.Completed += OnConnectCompleted;
                }
                connectEventArgs.RemoteEndPoint = endpoint;
                connectEventArgs.UserToken = socket;

                bool pending = socket.ConnectAsync(connectEventArgs);
                if (!pending)
                {
                    OnConnect(connectEventArgs);
                }
            }
            catch (Exception e)
            {
                Log.Error("{0} error connecting to {1} : {2}",
                    Name, endpoint, e.Message);

                OnConnectError(socket, endpoint);
            }
        }
        // constructors
        public BinaryConnection(ServerId serverId, EndPoint endPoint, ConnectionSettings settings, IStreamFactory streamFactory, IConnectionInitializer connectionInitializer, IEventSubscriber eventSubscriber)
        {
            Ensure.IsNotNull(serverId, nameof(serverId));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            _settings = Ensure.IsNotNull(settings, nameof(settings));
            _streamFactory = Ensure.IsNotNull(streamFactory, nameof(streamFactory));
            _connectionInitializer = Ensure.IsNotNull(connectionInitializer, nameof(connectionInitializer));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _backgroundTaskCancellationTokenSource = new CancellationTokenSource();
            _backgroundTaskCancellationToken = _backgroundTaskCancellationTokenSource.Token;

            _connectionId = new ConnectionId(serverId);
            _receiveLock = new SemaphoreSlim(1);
            _sendLock = new SemaphoreSlim(1);
            _state = new InterlockedInt32(State.Initial);

            _commandEventHelper = new CommandEventHelper(eventSubscriber);
            eventSubscriber.TryGetEventHandler(out _failedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _failedOpeningEventHandler);
            eventSubscriber.TryGetEventHandler(out _receivingMessageEventHandler);
            eventSubscriber.TryGetEventHandler(out _receivedMessageEventHandler);
            eventSubscriber.TryGetEventHandler(out _failedReceivingMessageEventHandler);
            eventSubscriber.TryGetEventHandler(out _sendingMessagesEventHandler);
            eventSubscriber.TryGetEventHandler(out _sentMessagesEventHandler);
            eventSubscriber.TryGetEventHandler(out _failedSendingMessagesEvent);
        }
 public NetworkDevice(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, EndPoint endPoint)
 {
     _AddressFamily = addressFamily;
     _SocketType = socketType;
     _ProtocolType = protocolType;
     _EndPoint = endPoint;
 }
Example #26
0
	protected UnixSocket (EndPoint localEndPoint)
		: base (System.Net.Sockets.AddressFamily.Unix,
		        System.Net.Sockets.SocketType.Stream,
		        System.Net.Sockets.ProtocolType.IP,
		        localEndPoint)
	{
	}
    private void SetupSocket()
    {
      if (udpSocket.IsBound)
        throw new ApplicationException("The socket is already bound and receving.");

      //recieve data from any source 
      localIPEndPoint = new IPEndPoint(IPAddress.Any, targetPort);
      localEndPoint = (EndPoint)localIPEndPoint;

      //init Socket properties:
      udpSocket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);

      //allow for loopback testing 
      udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

      //extremly important to bind the Socket before joining multicast groups 
      udpSocket.Bind(localIPEndPoint);

      //set multicast flags, sending flags - TimeToLive (TTL) 
      // 0 - LAN 
      // 1 - Single Router Hop 
      // 2 - Two Router Hops... 
      udpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, udpTTL);

      //join multicast group 
      udpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(targetIP)));

      NotifyMulticastSocketListener(MulticastSocketMessageType.SocketStarted, null);
    }
Example #28
0
 public PolicyConnection(PolicyServer policyServer, Socket client, byte[] policy)
 {
     _policyServer = policyServer;
     _connection = client;
     _endpoint = _connection.RemoteEndPoint;
     _policy = policy;
     _buffer = new byte[_policyRequestString.Length];
     _received = 0;
     try
     {
         // Receive the request from the client                
         _connection.BeginReceive(_buffer, 0, _policyRequestString.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
     }
     catch (SocketException ex)
     {
         if (log.IsDebugEnabled)
             log.Debug("Socket exception", ex);
         _connection.Close();
     }
     catch (Exception ex)
     {
         if (log.IsErrorEnabled)
             log.Error("Failed starting a policy connection", ex);
     }
 }
Example #29
0
 internal EndpointI(Instance instance, string ho, int po, EndPoint sourceAddr, int ti, string conId, bool co)
     : base(instance, ho, po, sourceAddr, conId)
 {
     _instance = instance;
     _timeout = ti;
     _compress = co;
 }
Example #30
0
        public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state)
        {
            // do nothing

            var r = new FakeAsyncResult(state);
            callback?.Invoke(r);
        }