コード例 #1
0
        /// <summary>
        /// Returns NetworkIdentifier.GetHashCode() ^ RemoteEndPoint.GetHashCode();
        /// </summary>
        /// <returns>The hashcode for this connection info</returns>
        public override int GetHashCode()
        {
            lock (internalLocker)
            {
                if (!hashCodeCacheSet)
                {
                    if (RemoteEndPoint != null & LocalEndPoint != null)
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ LocalEndPoint.GetHashCode() ^ RemoteEndPoint.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }
                    if (RemoteEndPoint != null)
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ RemoteEndPoint.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }
                    else if (LocalEndPoint != null)
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ LocalEndPoint.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }
                    else
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }

                    hashCodeCacheSet = true;
                }

                return(hashCodeCache);
            }
        }
コード例 #2
0
        /// <summary>
        /// 启动服务
        /// </summary>
        public void Start()
        {
            if (!IsRunning)
            {
                Init();

                IsRunning = true;

                // 创建监听socket
                _serverSock = new Socket(LocalEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                if (LocalEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    // 配置监听socket为 dual-mode (IPv4 & IPv6)
                    // 27 is equivalent to IPV6_V6ONLY socket option in the winsock snippet below,
                    _serverSock.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
                    _serverSock.Bind(new IPEndPoint(IPAddress.IPv6Any, LocalEndPoint.Port));
                }
                else
                {
                    _serverSock.Bind(LocalEndPoint);
                }
                // 开始监听
                _serverSock.Listen(this._maxClient);
                // 在监听Socket上投递一个接受请求。
                StartAccept(null);

                _daemonThread = new DaemonThread(this);

                Log4Debug("服务器已启动....[" + LocalEndPoint.ToString() + "]");
            }
        }
コード例 #3
0
        private void OnReceive(IAsyncResult state)
        {
            EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

            if (PortOpen)
            {
                try
                {
                    var receiveState = (ArtNetReceiveData)(state.AsyncState);

                    if (receiveState != null)
                    {
                        receiveState.DataLength = EndReceiveFrom(state, ref remoteEndPoint);

                        //Protect against UDP loopback where we receive our own packets.
                        if (!LocalEndPoint.Equals(remoteEndPoint) && receiveState.Valid)
                        {
                            LastPacket = DateTime.Now;

                            ProcessPacket((IPEndPoint)remoteEndPoint, ArtNetPacket.Create(receiveState, CustomPacketCreator));
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnUnhandledException(ex);
                }
                finally
                {
                    //Attempt to receive another packet.
                    StartReceive();
                }
            }
        }
コード例 #4
0
        protected Exception CreateTimeoutException(uint opaque)
        {
            const string kv            = "kv";
            var          correlationId = CreateCorrelationId(opaque);

            var context = new OperationContext(kv, correlationId)
            {
                BucketName          = Configuration.BucketName,
                LocalEndpoint       = LocalEndPoint.ToString(),
                RemoteEndpoint      = EndPoint.ToString(),
                TimeoutMicroseconds = Configuration.SendTimeout
            };

            var message = context.ToString();

            Log.Info(message);

            var exception = new SendTimeoutExpiredException(message);

            exception.Data.Add("ServiceType", kv);
            exception.Data.Add("CorrelationId", correlationId);
            exception.Data.Add("LocalEndpoint", LocalEndPoint.ToString());
            exception.Data.Add("Timeout", Configuration.SendTimeout);
            exception.Data.Add("RemoteEndpoint", EndPoint.ToString());
            return(exception);
        }
コード例 #5
0
        protected Exception CreateTimeoutException(uint opaque)
        {
            const string format = ", {0}", kv = "kv";
            var          correlationId = CreateCorrelationId(opaque);

            var builder = new StringBuilder(ExceptionUtil.OperationTimeout);

            builder.AppendFormat(format, kv);
            builder.AppendFormat(format, correlationId);
            builder.AppendFormat(format, LocalEndPoint);
            builder.AppendFormat(format, Configuration.SendTimeout);
            builder.AppendFormat(format, EndPoint);

            var message = builder.ToString();

            Log.Info(message);

            var exception = new SendTimeoutExpiredException(message);

            exception.Data.Add("ServiceType", kv);
            exception.Data.Add("CorrelationId", correlationId);
            exception.Data.Add("LocalEndpoint", LocalEndPoint.ToString());
            exception.Data.Add("Timeout", Configuration.SendTimeout);
            exception.Data.Add("RemoteEndpoint", EndPoint.ToString());
            return(exception);
        }
コード例 #6
0
        /// <summary>
        /// 查询设备目录请求
        /// </summary>
        /// <returns></returns>
        private SIPRequest QueryItems(SIPEndPoint remoteEndPoint, string remoteSIPId)
        {
            string fromTag = CallProperties.CreateNewTag();
            string toTag   = CallProperties.CreateNewTag();
            int    cSeq    = CallProperties.CreateNewCSeq();
            string callId  = CallProperties.CreateNewCallId();

            SIPURI        remoteUri = new SIPURI(RemoteSIPId, RemoteEndPoint.ToHost(), "");
            SIPURI        localUri  = new SIPURI(LocalSIPId, LocalEndPoint.ToHost(), "");
            SIPFromHeader from      = new SIPFromHeader(null, localUri, fromTag);
            //SIPToHeader to = new SIPToHeader(null, remoteUri, toTag);
            SIPToHeader to         = new SIPToHeader(null, remoteUri, null);
            SIPRequest  catalogReq = Transport.GetRequest(SIPMethodsEnum.MESSAGE, remoteUri);

            catalogReq.Header.From        = from;
            catalogReq.Header.Contact     = null;
            catalogReq.Header.Allow       = null;
            catalogReq.Header.To          = to;
            catalogReq.Header.UserAgent   = UserAgent;
            catalogReq.Header.CSeq        = cSeq;
            catalogReq.Header.CallId      = callId;
            catalogReq.Header.ContentType = "application/MANSCDP+xml";

            return(catalogReq);
        }
コード例 #7
0
        public override Task SendAsync(byte[] buffer, Func <SocketAsyncState, Task> callback, ISpan span, ErrorMap errorMap)
        {
            SocketAsyncState state = null;

            try
            {
                var opaque = Converter.ToUInt32(buffer, HeaderIndexFor.Opaque);
                state = new SocketAsyncState
                {
                    Data          = MemoryStreamFactory.GetMemoryStream(),
                    Opaque        = opaque,
                    Buffer        = buffer,
                    Completed     = callback,
                    SendOffset    = _eventArgs.Offset,
                    DispatchSpan  = span,
                    ConnectionId  = ContextId,
                    LocalEndpoint = LocalEndPoint.ToString(),
                    ErrorMap      = errorMap,
                    Timeout       = Configuration.SendTimeout
                };

                _eventArgs.UserToken = state;
                Log.Debug("Sending {0} with {1} on server {2}", state.Opaque, Identity, EndPoint);

                //set the buffer
                var bufferLength = buffer.Length < Configuration.BufferSize
                    ? buffer.Length
                    : Configuration.BufferSize;

                _eventArgs.SetBuffer(state.SendOffset, bufferLength);
                Buffer.BlockCopy(buffer, 0, _eventArgs.Buffer, state.SendOffset, bufferLength);

                //Send the request
                if (!Socket.SendAsync(_eventArgs))
                {
                    OnCompleted(Socket, _eventArgs);
                }
            }
            catch (Exception e)
            {
                if (state == null)
                {
                    callback(new SocketAsyncState
                    {
                        Exception = e,
                        Status    = (e is SocketException) ?
                                    ResponseStatus.TransportFailure :
                                    ResponseStatus.ClientFailure
                    });
                }
                else
                {
                    state.Exception = e;
                    state.Completed(state);
                    Log.Debug(e);
                }
            }

            return(Task.FromResult(0));
        }
コード例 #8
0
ファイル: Connection.cs プロジェクト: ShadyWhite/Milvaneth
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return(false);
            }

            return(obj is Connection connection && LocalEndPoint.Equals(connection.LocalEndPoint) && RemoteEndPoint.Equals(connection.RemoteEndPoint));
        }
コード例 #9
0
        public override int GetHashCode()
        {
            // ReSharper disable NonReadonlyMemberInGetHashCode
            if (LocalEndPoint == null | RemoteEndPoint == null)
            {
                return(-1);
            }

            return((LocalEndPoint.GetHashCode() + 0x0609) ^ RemoteEndPoint.GetHashCode());
            // ReSharper restore NonReadonlyMemberInGetHashCode
        }
コード例 #10
0
 private GossipNodeConfiguration(Builder builder)
 {
     BroadcastFrequency = builder.BroadcastFrequency ?? TimeSpan.FromSeconds(2);
     CompressionType    = builder.CompressionType;
     LocalEndPoint      = builder.LocalEndPoint ?? new IPEndPoint(IPAddress.Loopback, 29803);
     Logger             = (builder.LoggerConfiguration ?? new LoggerConfiguration())
                          .Destructure.AsScalar <IPEndPoint>()
                          .CreateLogger();
     Metadata = builder.Metadata;
     Name     = builder.Name ?? LocalEndPoint.ToString();
 }
コード例 #11
0
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return(false);
            }

            var connection = obj as Connection;

            return(LocalEndPoint.Equals(connection?.LocalEndPoint) && RemoteEndPoint.Equals(connection?.RemoteEndPoint));
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UdpListener"/> class.
        /// </summary>
        /// <param name="socket">The socket.</param>
        /// <param name="remote">The remote.</param>
        /// <param name="encoding">The encoding.</param>
        internal UdpListener(Socket socket, EndPoint remote, Encoding encoding)
        {
            this.socket = socket;

            LocalEndPoint  = socket.LocalEndPoint;
            RemoteEndPoint = remote;

            byte[] gb = Utils.Md5(LocalEndPoint.ToString());

            this.Guid = new Guid(gb);

            Sender = new UdpSender(socket, remote, this.Guid, encoding);
        }
コード例 #13
0
        public ServerSocket Start()
        {
            Log.InfoFormat("ServerSocket:Start LocalEndPoint:{0}", LocalEndPoint.ToString());
            _socket.Bind(LocalEndPoint);
            _socket.Listen(Backlog);
            _socket.ReceiveBufferSize = _socketSetting.ReceiveBufferSize;
            _socket.ReceiveTimeout    = _socketSetting.ReceiveTimeout;
            _socket.SendBufferSize    = _socketSetting.SendBufferSize;
            _socket.SendTimeout       = _socketSetting.SendTimeout;

            AcceptAsync(_acceptSocketAsyncEventArgs);
            return(this);
        }
コード例 #14
0
        /// <summary>
        /// Sends a memcached operation as a buffer to a the server.
        /// </summary>
        /// <param name="buffer">A memcached request buffer</param>
        /// <returns>A memcached response buffer.</returns>
        public override byte[] Send(byte[] buffer)
        {
            //create the state object and set it
            var opaque = Converter.ToUInt32(buffer, HeaderIndexFor.Opaque);
            var state  = new SocketAsyncState
            {
                Data          = MemoryStreamFactory.GetMemoryStream(),
                Opaque        = opaque,
                Buffer        = buffer,
                SendOffset    = _eventArgs.Offset,
                ConnectionId  = ContextId,
                LocalEndpoint = LocalEndPoint.ToString(),
                Timeout       = Configuration.SendTimeout
            };

            Log.Debug("Sending opaque{0} on {1}", state.Opaque, Identity);
            _eventArgs.UserToken = state;

            //set the buffer
            var bufferLength = buffer.Length < Configuration.BufferSize
                ? buffer.Length
                : Configuration.BufferSize;

            _eventArgs.SetBuffer(state.SendOffset, bufferLength);
            Buffer.BlockCopy(buffer, 0, _eventArgs.Buffer, state.SendOffset, bufferLength);

            //Send the request
            if (!Socket.SendAsync(_eventArgs))
            {
                OnCompleted(Socket, _eventArgs);
            }

            //wait for completion
            if (!_requestCompleted.WaitOne(Configuration.SendTimeout))
            {
                IsDead = true;
                throw CreateTimeoutException(opaque);
            }

            //Check if an IO error occurred
            if (state.Exception != null)
            {
                Log.Debug("Connection {0} has failed with {1}", Identity, state.Exception);
                IsDead = true;
                throw state.Exception;
            }

            Log.Debug("Complete opaque{0} on {1}", state.Opaque, Identity);
            //return the response bytes
            return(state.Data.ToArray());
        }
コード例 #15
0
        /// <summary>
        /// Returns a string containing suitable information about this connection
        /// </summary>
        /// <returns>A string containing suitable information about this connection</returns>
        public override string ToString()
        {
            //Add a useful connection state identifier
            string connectionStateIdentifier;

            switch (ConnectionState)
            {
            case ConnectionState.Undefined:
                connectionStateIdentifier = "U";
                break;

            case ConnectionState.Establishing:
                connectionStateIdentifier = "I";
                break;

            case ConnectionState.Established:
                connectionStateIdentifier = "E";
                break;

            case ConnectionState.Shutdown:
                connectionStateIdentifier = "S";
                break;

            default:
                throw new Exception("Unexpected connection state.");
            }

            string returnString = "[" + ConnectionType.ToString() + "-" + (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? "E" : "D") + "-" + connectionStateIdentifier + "] ";

            if (RemoteEndPoint != null && LocalEndPoint != null)
            {
                returnString += LocalEndPoint.ToString() + " -> " + RemoteEndPoint.ToString();
            }
            else if (RemoteEndPoint != null)
            {
                returnString += "Local -> " + RemoteEndPoint.ToString();
            }
            else if (LocalEndPoint != null)
            {
                returnString += LocalEndPoint.ToString() + " " + (IsConnectable ? "Connectable" : "NotConnectable");
            }

            if (NetworkIdentifier != ShortGuid.Empty)
            {
                returnString += " (" + NetworkIdentifier + ")";
            }

            return(returnString.Trim());
        }
コード例 #16
0
        /// <summary>
        /// Executes after listener was started.
        /// </summary>
        private static void ListenerService_OnStarted()
        {
            Service.NetworkListenerIsActive = true;

            // audit record
            DataProvider.DataBase.ServiceAudit
            (
                Settings.Default.ServiceUniqueID,
                ( byte )ServiceType.CacheService,
                ServiceAuditType.NetworkListenerStarted,
                LocalEndPoint.ToString()
            );

            Logger.WriteLine(Source.Listener, "Network listener started on {0}", m_ListenerService.LocalEndPoint);
        }
 /// <summary>
 /// Returns a <see cref="System.String" /> that represents this instance.
 /// </summary>
 /// <returns>
 /// A <see cref="System.String" /> that represents this instance.
 /// </returns>
 public override string ToString()
 {
     return(String.Format(
                "LocalEndPoint: {1}{0}" +
                "RemoteEndPoint: {2}{0}" +
                "State: {3}{0}" +
                "Pid:{4}{0}" +
                "Process: {5}",
                Environment.NewLine,
                LocalEndPoint.ToString(),
                RemoteEndPoint.ToString(),
                State,
                ProcessId,
                Process.ProcessName));
 }
コード例 #18
0
        public async Task SendAsync(ReadOnlyMemory <byte> request, Action <IMemoryOwner <byte>, ResponseStatus> callback, ErrorMap?errorMap = null)
        {
            if (request.Length >= MaxDocSize)
            {
                throw new ValueToolargeException("Encoded document exceeds the 20MB document size limit.");
            }
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(MultiplexingConnection));
            }

            var opaque = ByteConverter.ToUInt32(request.Span.Slice(HeaderOffsets.Opaque));
            var state  = new AsyncState(callback, opaque)
            {
                EndPoint      = (IPEndPoint)EndPoint,
                ConnectionId  = ConnectionId,
                ErrorMap      = errorMap,
                LocalEndpoint = LocalEndPoint.ToString()
            };

            _statesInFlight.Add(state, 75000);

            await _writeMutex.GetLockAsync().ConfigureAwait(false);

            try
            {
#if NETCOREAPP2_1 || NETCOREAPP3_0 || NETSTANDARD2_1
                await _stream.WriteAsync(request).ConfigureAwait(false);
#else
                if (!MemoryMarshal.TryGetArray <byte>(request, out var arraySegment))
                {
                    // Fallback in case we can't use the more efficient TryGetArray method
                    arraySegment = new ArraySegment <byte>(request.ToArray());
                }

                await _stream.WriteAsync(arraySegment.Array, arraySegment.Offset, arraySegment.Count)
                .ConfigureAwait(false);
#endif
            }
            catch (Exception e)
            {
                HandleDisconnect(e);
            }
            finally
            {
                _writeMutex.ReleaseLock();
            }
        }
コード例 #19
0
ファイル: ShardSession.cs プロジェクト: soulson/whisper
        /// <summary>
        /// Sends the specified ArraySegment as a packet to the client.
        /// </summary>
        /// <param name="segment">packet</param>
        public override void Send(ArraySegment <byte> segment)
        {
            if (packetLog.IsInfoEnabled && segment.Count >= 4)
            {
                ShardServerOpcode opcode  = (ShardServerOpcode)BitConverter.ToUInt16(segment.Array, segment.Offset + 2);
                ushort            size    = BitConverter.ToUInt16(new byte[] { segment.Array[segment.Offset + 1], segment.Array[segment.Offset] }, 0); // big endian
                string            hexDump = Strings.HexDump(segment.Array, segment.Offset + 4, size - sizeof(ushort));                                 // sizeof the opcode

                packetLog.InfoFormat("Server [{0}] -> Client [{1}]", LocalEndPoint.ToString(), RemoteEndPoint.ToString());
                packetLog.InfoFormat("Opcode: {0} [0x{1:x4}]", opcode, (ushort)opcode);
                packetLog.InfoFormat("Length: {0}", size - sizeof(ushort));
                packetLog.InfoFormat("{1}{0}{1}", hexDump, Environment.NewLine);
            }

            Cipher.EncryptHeader(segment);
            base.Send(segment);
        }
コード例 #20
0
        private async Task <byte[]> SendAsync(byte[] buffer, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var opaque = Converter.ToUInt32(buffer, HeaderIndexFor.Opaque);
            var state  = new SocketAsyncState
            {
                Data          = MemoryStreamFactory.GetMemoryStream(),
                Opaque        = opaque,
                ConnectionId  = ContextId,
                LocalEndpoint = LocalEndPoint.ToString(),
                Timeout       = Configuration.SendTimeout
            };

            await _sslStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken).ContinueOnAnyContext();

            state.SetIOBuffer(_buffer);

            while (state.BytesReceived < state.BodyLength + OperationHeader.Length)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var bytesReceived = await _sslStream
                                    .ReadAsync(state.Buffer, state.BufferOffset, state.BufferLength, cancellationToken)
                                    .ContinueOnAnyContext();

                state.BytesReceived += bytesReceived;

                if (state.BytesReceived == 0)
                {
                    // No more bytes were received, go ahead and exit the loop
                    break;
                }

                if (state.BodyLength == 0)
                {
                    // Reading header, so get the BodyLength
                    state.BodyLength = Converter.ToInt32(state.Buffer, state.BufferOffset + HeaderIndexFor.Body);
                }

                state.Data.Write(state.Buffer, state.BufferOffset, bytesReceived);
            }

            return(state.Data.ToArray());
        }
コード例 #21
0
        public override Task SendAsync(byte[] request, Func <SocketAsyncState, Task> callback, ISpan span, ErrorMap errorMap)
        {
            var opaque = Converter.ToUInt32(request, HeaderIndexFor.Opaque);
            var state  = new AsyncState
            {
                Opaque        = opaque,
                Callback      = callback,
                Converter     = Converter,
                EndPoint      = (IPEndPoint)EndPoint,
                DispatchSpan  = span,
                ConnectionId  = ContextId,
                ErrorMap      = errorMap,
                Timeout       = Configuration.SendTimeout,
                LocalEndpoint = LocalEndPoint.ToString()
            };

            _statesInFlight.TryAdd(state.Opaque, state);

            state.Timer = new Timer(o =>
            {
                AsyncState a = (AsyncState)o;
                _statesInFlight.TryRemove(a.Opaque, out _);
                a.Cancel(ResponseStatus.OperationTimeout, CreateTimeoutException(opaque));
            }, state, Configuration.SendTimeout, Timeout.Infinite);

            var sentBytesCount = 0;

            lock (Socket)
            {
                try
                {
                    do
                    {
                        sentBytesCount += Socket.Send(request, sentBytesCount, request.Length - sentBytesCount,
                                                      SocketFlags.None);
                    } while (sentBytesCount < request.Length);
                }
                catch (Exception e)
                {
                    HandleDisconnect(e);
                }
            }

            return(Task.FromResult(0));
        }
コード例 #22
0
        private EpoxyConnection(
            ConnectionType connectionType,
            EpoxyTransport parentTransport,
            EpoxyListener parentListener,
            ServiceHost serviceHost,
            Socket socket,
            Logger logger,
            Metrics metrics)
        {
            Debug.Assert(parentTransport != null);
            Debug.Assert(connectionType != ConnectionType.Server || parentListener != null, "Server connections must have a listener");
            Debug.Assert(serviceHost != null);
            Debug.Assert(socket != null);

            this.connectionType = connectionType;

            this.parentTransport = parentTransport;
            this.parentListener  = parentListener;
            this.serviceHost     = serviceHost;

            netSocket = new EpoxySocket(socket, logger);

            // cache these so we can use them after the socket has been shutdown
            LocalEndPoint  = (IPEndPoint)socket.LocalEndPoint;
            RemoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;

            responseMap = new ResponseMap();

            state               = State.Created;
            startTask           = new TaskCompletionSource <bool>();
            stopTask            = new TaskCompletionSource <bool>();
            shutdownTokenSource = new CancellationTokenSource();

            // start at -1 or 0 so the first conversation ID is 1 or 2.
            prevConversationId = (connectionType == ConnectionType.Client) ? -1 : 0;

            connectionMetrics.connection_id   = Guid.NewGuid().ToString();
            connectionMetrics.local_endpoint  = LocalEndPoint.ToString();
            connectionMetrics.remote_endpoint = RemoteEndPoint.ToString();

            this.logger  = logger;
            this.metrics = metrics;
        }
コード例 #23
0
 /// <summary>
 ///  Returns the hashcode for this object.
 /// </summary>
 /// <returns></returns>
 /// <remarks>
 /// Excluding those properties which are not serialized:
 /// ClientCertificates, ServerCertificateValidationCallback, NetworkCredential, ProtocolLoggerDelegate
 /// </remarks>
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = MaxFailures;
         hashCode = (hashCode * 397) ^ RetryDelayTime;
         hashCode = (hashCode * 397) ^ (MailOutputDirectory != null ? MailOutputDirectory.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (SmtpHost != null ? SmtpHost.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ SmtpPort;
         hashCode = (hashCode * 397) ^ (ClientDomain != null ? ClientDomain.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (LocalEndPoint != null ? LocalEndPoint.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (int)MessageOutput;
         hashCode = (hashCode * 397) ^ (int)SslProtocols;
         hashCode = (hashCode * 397) ^ (int)SecureSocketOptions;
         hashCode = (hashCode * 397) ^ Timeout;
         hashCode = (hashCode * 397) ^ DelayBetweenMessages;
         return(hashCode);
     }
 }
コード例 #24
0
ファイル: ManagedSocket.cs プロジェクト: wilson0x4d/DataRelay
        public void Connect(IPEndPoint remoteEndPoint, int timeoutMilliseconds)
        {
            _remoteEndPoint = remoteEndPoint;
            IAsyncResult asyncResult = BeginConnect(remoteEndPoint, null, null);

            // there is no other way to set a time out on a connection other than putting a time out on the wait here and manually throwing an exception
            if (!asyncResult.AsyncWaitHandle.WaitOne(timeoutMilliseconds, false))
            {
                Close();
                throw new SocketException((int)SocketError.HostUnreachable);
            }

            EndConnect(asyncResult);

            _localEndPoint = LocalEndPoint.ToString();

            BeginReceive(GetReceiveBuffer(_settings.ReceiveBufferSize), 0, _settings.ReceiveBufferSize, SocketFlags.None,
                         ReceiveCallback, null);                         //start a receive immediately so there's always one running. otherwise we have no way to detect if the connection is closed

            CheckServerCapabilities();
        }
コード例 #25
0
ファイル: EpoxyConnection.cs プロジェクト: xrcdev/bond
        private EpoxyConnection(
            ConnectionType connectionType,
            EpoxyTransport parentTransport,
            EpoxyListener parentListener,
            ServiceHost serviceHost,
            EpoxyNetworkStream networkStream,
            Logger logger,
            Metrics metrics)
        {
            Debug.Assert(parentTransport != null);
            Debug.Assert(connectionType != ConnectionType.Server || parentListener != null, "Server connections must have a listener");
            Debug.Assert(serviceHost != null);
            Debug.Assert(networkStream != null);

            this.connectionType = connectionType;

            this.parentTransport = parentTransport;
            this.parentListener  = parentListener;
            this.serviceHost     = serviceHost;

            this.networkStream = networkStream;

            responseMap = new ResponseMap();

            state               = State.Created;
            startTask           = new TaskCompletionSource <bool>();
            stopTask            = new TaskCompletionSource <bool>();
            shutdownTokenSource = new CancellationTokenSource();

            // start at -1 or 0 so the first conversation ID is 1 or 2.
            prevConversationId = (connectionType == ConnectionType.Client) ? -1 : 0;

            ConnectionMetrics.local_endpoint  = LocalEndPoint.ToString();
            ConnectionMetrics.remote_endpoint = RemoteEndPoint.ToString();

            this.logger  = logger;
            this.metrics = metrics;
        }
コード例 #26
0
        /// <summary>
        /// 向上级平台注册
        /// </summary>
        private void RegisterToPlatform()
        {
            string fromTag = CallProperties.CreateNewTag();
            string callId  = CallProperties.CreateNewCallId();
            int    cSeq    = CallProperties.CreateNewCSeq();
            string branch  = CallProperties.CreateBranchId();

            SIPURI     localUri    = new SIPURI(LocalSIPId, LocalEndPoint.ToHost(), "");
            SIPURI     remoteUri   = new SIPURI(RemoteSIPId, RemoteEndPoint.ToHost(), "");
            SIPRequest registerReq = new SIPRequest(SIPMethodsEnum.REGISTER, remoteUri);

            SIPViaHeader via    = new SIPViaHeader(LocalEndPoint, branch);
            SIPViaSet    viaSet = new SIPViaSet();

            viaSet.PushViaHeader(via);

            SIPFromHeader from   = new SIPFromHeader(null, localUri, fromTag);
            SIPToHeader   to     = new SIPToHeader(null, localUri, null);
            SIPHeader     header = new SIPHeader(from, to, cSeq, callId);

            registerReq.Header = header;

            SIPContactHeader contact = new SIPContactHeader(null, localUri);

            header.Contact = new List <SIPContactHeader>();
            header.Contact.Add(contact);

            header.Vias = viaSet;

            header.AuthenticationHeader = _auth;

            header.Expires       = 3600;
            header.CSeqMethod    = SIPMethodsEnum.REGISTER;
            header.MaxForwards   = 70;
            header.ContentLength = 0;
            header.UserAgent     = SIPConstants.SIP_SERVER_STRING;
            Transport.SendRequest(RemoteEndPoint, registerReq);
        }
コード例 #27
0
        public MultiplexingConnection(Stream stream, EndPoint localEndPoint, EndPoint remoteEndPoint,
                                      ILogger <MultiplexingConnection> logger)
        {
            _stream       = stream ?? throw new ArgumentNullException(nameof(stream));
            LocalEndPoint = localEndPoint ?? throw new ArgumentNullException(nameof(localEndPoint));
            EndPoint      = remoteEndPoint ?? throw new ArgumentNullException(nameof(remoteEndPoint));
            _logger       = logger ?? throw new ArgumentNullException(nameof(logger));

            ConnectionId = ConnectionIdProvider.GetNextId();

            _endPointString      = EndPoint.ToString() ?? DiagnosticsReportProvider.UnknownEndpointValue;
            _localEndPointString = LocalEndPoint.ToString() ?? DiagnosticsReportProvider.UnknownEndpointValue;
            _connectionIdString  = ConnectionId.ToString(CultureInfo.InvariantCulture);

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            // We don't need the execution context to flow to the receive loop
            using (ExecutionContext.SuppressFlow())
            {
                Task.Run(ReceiveResponsesAsync);
            }
        }
コード例 #28
0
        protected OperationContext CreateOperationContext(uint opaque)
        {
            var context = OperationContext.CreateKvContext(opaque);

            context.ConnectionId = ContextId;

            if (Configuration != null)
            {
                context.BucketName          = Configuration.BucketName;
                context.TimeoutMicroseconds = (uint)Configuration.SendTimeout * 1000;  // convert millis to micros
            }

            if (LocalEndPoint != null)
            {
                context.LocalEndpoint = LocalEndPoint.ToString();
            }

            if (EndPoint != null)
            {
                context.RemoteEndpoint = EndPoint.ToString();
            }

            return(context);
        }
コード例 #29
0
ファイル: ConnectionListener.cs プロジェクト: rflechner/swan
 /// <summary>
 /// Returns a <see cref="System.String" /> that represents this instance.
 /// </summary>
 /// <returns>
 /// A <see cref="System.String" /> that represents this instance.
 /// </returns>
 public override string ToString() => LocalEndPoint.ToString();
コード例 #30
0
        public Task SendAsync(ReadOnlyMemory <byte> request, Func <SocketAsyncState, Task> callback, ErrorMap errorMap)
        {
            var opaque = Converter.ToUInt32(request.Span.Slice(HeaderOffsets.Opaque));
            var state  = new AsyncState
            {
                Opaque        = opaque,
                Callback      = callback,
                Converter     = Converter,
                EndPoint      = (IPEndPoint)EndPoint,
                ConnectionId  = ConnectionId,
                ErrorMap      = errorMap,
                LocalEndpoint = LocalEndPoint.ToString()
            };

            _statesInFlight.TryAdd(state.Opaque, state);

            state.Timer = new Timer(o =>
            {
                AsyncState a = (AsyncState)o;
                _statesInFlight.TryRemove(a.Opaque, out _);
                a.Cancel(ResponseStatus.OperationTimeout, new TimeoutException());
            }, state, 75000, Timeout.Infinite);


            lock (Socket)
            {
                try
                {
                    #if NETCOREAPP2_1
                    var requestSpan = request.Span;
                    while (requestSpan.Length > 0)
                    {
                        var sentBytesCount = Socket.Send(requestSpan, SocketFlags.None);

                        requestSpan = requestSpan.Slice(sentBytesCount);
                    }
                    #else
                    if (!MemoryMarshal.TryGetArray <byte>(request, out var arraySegment))
                    {
                        // Fallback in case we can't use the more efficient TryGetArray method
                        arraySegment = new ArraySegment <byte>(request.ToArray());
                    }

                    var sentBytesCount = 0;
                    do
                    {
                        // ReSharper disable once AssignNullToNotNullAttribute
                        sentBytesCount += Socket.Send(arraySegment.Array,
                                                      arraySegment.Offset + sentBytesCount,
                                                      arraySegment.Count - sentBytesCount,
                                                      SocketFlags.None);
                    } while (sentBytesCount < arraySegment.Count);
                    #endif
                }
                catch (Exception e)
                {
                    HandleDisconnect(e);
                }
            }

            return(Task.FromResult(0));
        }