示例#1
0
        private void Read(List <byte> data, byte[] buffer)
        {
            if (!IsAvailable)
            {
                return;
            }

            Socket.Receive(buffer, r => {
                if (r <= 0)
                {
                    NTWebSocketLog.Debug("0 bytes read. Closing.");
                    CloseSocket();
                    return;
                }
                NTWebSocketLog.Debug(r + " bytes read");
                var readBytes = buffer.Take(r);
                if (Handler != null)
                {
                    Handler.Receive(readBytes);
                }
                else
                {
                    data.AddRange(readBytes);
                    CreateHandler(data);
                }

                Read(data, buffer);
            },
                           HandleReadError);
        }
示例#2
0
        public void Start(Action <IWebSocketConnection> config)
        {
            var ipLocal = new IPEndPoint(_locationIP, Port);

            ListenerSocket.Bind(ipLocal);
            ListenerSocket.Listen(100);
            Port = ((IPEndPoint)ListenerSocket.LocalEndPoint).Port;
            NTWebSocketLog.Info(string.Format("Server started at {0} (actual port {1})", Location, Port));
            if (_scheme == "wss")
            {
                if (Certificate == null)
                {
                    NTWebSocketLog.Error("Scheme cannot be 'wss' without a Certificate");
                    return;
                }

                if (EnabledSslProtocols == SslProtocols.None)
                {
                    EnabledSslProtocols = SslProtocols.Tls;
                    NTWebSocketLog.Debug("Using default TLS 1.0 security protocol.");
                }
            }
            ListenForClients();
            _config = config;
        }
示例#3
0
 private void ListenForClients()
 {
     ListenerSocket.Accept(OnClientConnect, e => {
         NTWebSocketLog.Error("Listener socket is closed", e);
         if (RestartAfterListenError)
         {
             NTWebSocketLog.Info("Listener socket restarting");
             try {
                 ListenerSocket.Dispose();
                 var socket     = new Socket(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP);
                 ListenerSocket = new SocketWrapper(socket);
                 Start(_config);
                 NTWebSocketLog.Info("Listener socket restarted");
             }
             catch (Exception ex) {
                 NTWebSocketLog.Error("Listener could not be restarted", ex);
             }
         }
     });
 }
示例#4
0
 private Task SendBytes(byte[] bytes, Action callback = null)
 {
     return(Socket.Send(bytes, () => {
         NTWebSocketLog.Debug("Sent " + bytes.Length + " bytes");
         if (callback != null)
         {
             callback();
         }
     },
                        e => {
         if (e is IOException)
         {
             NTWebSocketLog.Debug("Failed to send. Disconnecting.", e);
         }
         else
         {
             NTWebSocketLog.Info("Failed to send. Disconnecting.", e);
         }
         CloseSocket();
     }));
 }
示例#5
0
        private Task Send <T>(T message, Func <T, byte[]> createFrame)
        {
            if (Handler == null)
            {
                throw new InvalidOperationException("Cannot send before handshake");
            }

            if (!IsAvailable)
            {
                const string errorMessage = "Data sent while closing or after close. Ignoring.";
                NTWebSocketLog.Warn(errorMessage);

                var taskForException = new TaskCompletionSource <object>();
                taskForException.SetException(new ConnectionNotAvailableException(errorMessage));
                return(taskForException.Task);
            }

            var bytes = createFrame(message);

            return(SendBytes(bytes));
        }
示例#6
0
        private void HandleReadError(Exception e)
        {
            if (e is AggregateException)
            {
                var agg = e as AggregateException;
                HandleReadError(agg.InnerException);
                return;
            }

            if (e is ObjectDisposedException)
            {
                NTWebSocketLog.Debug("Swallowing ObjectDisposedException", e);
                return;
            }

            OnError(e);

            if (e is WebSocketException)
            {
                NTWebSocketLog.Debug("Error while reading", e);
                Close(((WebSocketException)e).StatusCode);
            }
            else if (e is SubProtocolNegotiationFailureException)
            {
                NTWebSocketLog.Debug(e.Message);
                Close(WebSocketStatusCodes.ProtocolError);
            }
            else if (e is IOException)
            {
                NTWebSocketLog.Debug("Error while reading", e);
                Close(WebSocketStatusCodes.AbnormalClosure);
            }
            else
            {
                NTWebSocketLog.Error("Application Error", e);
                Close(WebSocketStatusCodes.InternalServerError);
            }
        }
示例#7
0
        private void OnClientConnect(ISocket clientSocket)
        {
            if (clientSocket == null)
            {
                return;                       // socket closed
            }
            NTWebSocketLog.Debug(String.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));
            ListenForClients();

            WebSocketConnection connection = null;

            connection = new WebSocketConnection(
                clientSocket,
                initialize: _config,
                parseRequest: bytes => RequestParser.Parse(bytes, _scheme),
                handlerFactory: r => HandlerFactory.BuildHandler(
                    request: r,
                    onMessage: s => connection.OnMessage(s),
                    onClose: connection.Close,
                    onBinary: b => connection.OnBinary(b),
                    onPing: b => connection.OnPing(b),
                    onPong: b => connection.OnPong(b)),
                negotiateSubProtocol: s => SubProtocolNegotiator.Negotiate(SupportedSubProtocols, s));

            if (IsSecure)
            {
                NTWebSocketLog.Debug("Authenticating Secure Connection");
                clientSocket
                .Authenticate(Certificate,
                              EnabledSslProtocols,
                              connection.StartReceiving,
                              e => NTWebSocketLog.Warn("Failed to Authenticate", e));
            }
            else
            {
                connection.StartReceiving();
            }
        }