Пример #1
0
        /// <summary>
        /// Disposes the current object.
        /// </summary>
        /// <param name="closeConnection">Close the connection if it is running.</param>
        /// <param name="closed">If the connection is closed.</param>
        /// <returns>Returns the completed task.</returns>
        public async ValueTask DisposeAsync(bool closeConnection, bool closed = false)
        {
            if (disposed)
            {
                return;
            }
            disposed = true;
            if (closeConnection && !closed)
            {
                closed = true;
                await CloseAsync(WebSocketCloseStatus.NormalClosure, "");
            }

            closed = true;
            NetworkStream?stream = null;

            if (!closed)
            {
                stream = client.GetStream();
            }
            if (secure && !closed)
            {
                await secureStream.DisposeAsync();
            }
            else if (!closed)
            {
                await stream.DisposeAsync();
            }
            else if (!closed)
            {
                client.Dispose();
            }
        }
Пример #2
0
        private async Task <bool> TryConnect()
        {
            if (connection != null)
            {
                return(true);
            }

            if (config == null || string.IsNullOrWhiteSpace(config.Address))
            {
                return(false);
            }

            try {
                var(host, port) = GetHostAndPort(config);

                connection                = new TcpClient();
                connection.SendTimeout    = TimeOutMS;
                connection.ReceiveTimeout = TimeOutMS;
                await connection.ConnectAsync(host, port);

                networkStream = connection.GetStream();

                this.mapId2Info = config.GetAllDataItems().Where(di => !string.IsNullOrEmpty(di.Address)).ToDictionary(
                    item => /* key */ item.ID,
                    item => /* val */ new ItemInfo(item, GetModbusAddress(item)));

                return(true);
            }
            catch (Exception exp) {
                Exception baseExp = exp.GetBaseException() ?? exp;
                LogWarn("Connect", "Connection error: " + baseExp.Message, details: baseExp.StackTrace);
                CloseConnection();
                return(false);
            }
        }
Пример #3
0
        public async Task <bool> EnsureConnectedAsync(CancellationToken cancellationToken = default)
        {
            var needsToReConnect = !this._tcpClient.Connected;

            if (needsToReConnect)
            {
                await this._tcpClient.ConnectAsync(this._ipAddress, this._port, cancellationToken).ConfigureAwait(false);

                if (this._sslStream != null)
                {
                    this._sslStream.Close();
                    this._sslStream.Dispose();
                    this._sslStream = null;
                }
                if (this._nsStream != null)
                {
                    this._nsStream.Close();
                    this._nsStream.Dispose();
                }
                this._nsStream = this._tcpClient.GetStream();
                if (this._useSsl)
                {
                    this._sslStream = new SslStream(this._nsStream, true, this.IsCertificateValid !);
                    this._sslStream.AuthenticateAsClient(this._host);
                }
            }
            return(needsToReConnect);
        }
Пример #4
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                // release managed resources
                NetworkStream?s = stream;
                stream = null;
                if (s != null)
                {
                    // This closes the socket as well, as the NetworkStream
                    // owns the socket.
                    s.Close();
                    s = null;
                }
                else if (client != null)
                {
                    client.Close();
                }
            }

            disposed = true;
        }
Пример #5
0
        User NewUser(NetworkStream?stream, Dictionary <string, object> obj)
        {
            User currentuser = new User((string)obj["name"], (string)obj["uid"]);

            if (Rules.BlueUser > Rules.RedUser)
            {
                currentuser.group = 1;
            }
            else
            {
                currentuser.group = 0;
            }

            if ((int)Convert.ToInt32(obj["group"]) == 0)
            {
                Rules.BlueUser++;
            }
            else if ((int)Convert.ToInt32(obj["group"]) == 1)
            {
                Rules.RedUser++;
            }


            currentuser.Health      = (int)Convert.ToInt32(obj["health"]);
            currentuser.SolderClass = (int)Convert.ToInt32(obj["solderclass"]);

            Console.WriteLine($"Room {PORT} new User {currentuser.name}:{currentuser.uId}" +
                              $"\nUser Wanna play in {obj["group"]} group but w`ll be play in {currentuser.group} now user in room {Users.Count}");
            return(currentuser);
        }
Пример #6
0
        // Returns the stream used to read and write data to the remote host.
        public NetworkStream GetStream()
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }

            ThrowIfDisposed();

            if (!Connected)
            {
                throw new InvalidOperationException(SR.net_notconnected);
            }

            if (_dataStream == null)
            {
                _dataStream = new NetworkStream(Client, true);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Exit(this, _dataStream);
            }
            return(_dataStream);
        }
Пример #7
0
        public bool Start(string ipAddress)
        {
            int port     = 9001;
            var endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
            var socket   = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            Console.WriteLine("Waiting to connect...");

            int attempts = 0;

            while (!socket.Connected && attempts < 5)
            {
                try { socket.Connect(endPoint); }
                catch (SocketException)
                {
                    attempts++;
                    Task.Delay(TimeSpan.FromSeconds(1)).Wait();
                }
            }

            if (!socket.Connected)
            {
                Console.WriteLine("Failed to connect");
                return(false);
            }

            Console.WriteLine("Connected");

            Stream = new NetworkStream(socket, true);
            return(true);
        }
Пример #8
0
        protected override async ValueTask ClientHandshakeAsync(CancellationToken token)
        {
            _client = new();
            await _client.ConnectAsync(Host !, Port, token);

            _netStream = _client.GetStream();
        }
        public void SslStreamCtor(SslStream sslStream, Stream innerStream)
        {
            if (IsEnabled())
            {
                string?localId  = null;
                string?remoteId = null;

                NetworkStream?ns = innerStream as NetworkStream;
                if (ns != null)
                {
                    try
                    {
                        localId  = ns.Socket.LocalEndPoint?.ToString();
                        remoteId = ns.Socket.RemoteEndPoint?.ToString();
                    }
                    catch { };
                }

                if (localId == null)
                {
                    localId = IdOf(innerStream);
                }

                SslStreamCtor(IdOf(sslStream), localId, remoteId);
            }
        }
Пример #10
0
        /// <summary>
        /// Connects to the specified TCP port on the specified host
        /// </summary>
        public async Task ConnectAsync(string hostname, Port port)
        {
            if (string.IsNullOrEmpty(hostname)) throw new ArgumentNullException(nameof(hostname));
            if (port.IsNone) throw new ArgumentException("Port must be defined", nameof(port));

            await _tcpClient.ConnectAsync(hostname, port.Number);
            _stream = _tcpClient.GetStream();
        }
Пример #11
0
 public void Connect(string host, int port)
 {
     closed                    = false;
     connection                = new TcpClient();
     connection.SendTimeout    = SendTimeout;
     connection.ReceiveTimeout = 0;
     connection.Connect(host, port);
     networkStream = connection.GetStream();
 }
Пример #12
0
        public NetworkStream GetStream()
        {
            CheckDisposed();
            if (stream == null)
            {
                stream = new NetworkStream(client, true);
            }

            return(stream);
        }
Пример #13
0
        public async Task ConnectAsync(string host, int port)
        {
            closed                    = false;
            connection                = new TcpClient();
            connection.SendTimeout    = SendTimeout;
            connection.ReceiveTimeout = 0;
            await connection.ConnectAsync(host, port);

            networkStream = connection.GetStream();
        }
Пример #14
0
        /// <inheritdoc/>
        public async Task OpenAsync()
        {
            try
            {
                _client = new System.Net.Sockets.TcpClient();
                await _client.ConnectAsync(_hostName, _port);

                _networkStream = _client.GetStream();
            }
            catch (Exception e)
            {
                throw new ConnectFailedException($"建立TCP连接失败:{_hostName}:{_port}", e);
            }
        }
Пример #15
0
        public void Dispose()
        {
            _sslOverTdsStream?.Dispose();
            _sslOverTdsStream = null;
            _sslStream?.Dispose();
            _sslStream = null;
            _tcpStream?.Dispose();
            _tcpStream = null;

            //Release any references held by _stream.
            _stream = null;
            _socket?.Dispose();
            _socket = null;
        }
Пример #16
0
 public void Close()
 {
     if (connection != null && !closed)
     {
         try {
             closed = true;
             networkStream?.Close(0);
             connection.Close();
             networkStream = null;
             connection    = null;
         }
         catch (Exception) { }
     }
 }
Пример #17
0
        private void ConnectCompleted(bool success)
        {
            // Always discard result if our request was cancelled
            // If we have no cancellation token source, we were already Release()'ed
            if (cancellationToken?.IsCancellationRequested ?? true)
            {
                log.LogDebug(nameof(TcpConnection), "Connection request to {0} was cancelled", CurrentEndPoint);
                if (success)
                {
                    Shutdown();
                }
                Release(userRequestedDisconnect: true);
                return;
            }
            else if (!success)
            {
                log.LogDebug(nameof(TcpConnection), "Failed connecting to {0}", CurrentEndPoint);
                Release(userRequestedDisconnect: false);
                return;
            }

            log.LogDebug(nameof(TcpConnection), "Connected to {0}", CurrentEndPoint);
            DebugLog.Assert(socket != null, nameof(TcpConnection), "Socket should be non-null after connecting.");

            try
            {
                lock (netLock)
                {
                    netStream = new NetworkStream(socket, false);
                    netReader = new BinaryReader(netStream);
                    netWriter = new BinaryWriter(netStream);

                    netThread = new Thread(NetLoop)
                    {
                        Name = "SK2-TcpConn"
                    };

                    CurrentEndPoint = socket !.RemoteEndPoint;
                }

                netThread.Start();

                Connected?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                log.LogDebug(nameof(TcpConnection), "Exception while setting up connection to {0}: {1}", CurrentEndPoint, ex);
                Release(userRequestedDisconnect: false);
            }
        }
Пример #18
0
        protected virtual void Dispose(bool disposing)
        {
            Board?.Dispose();
            if (_networkStream != null)
            {
                _networkStream.Dispose();
                _networkStream = null;
            }

            if (_socket != null)
            {
                _socket.Close();
                _socket.Dispose();
                _socket = null;
            }
        }
Пример #19
0
        // Returns the stream used to read and write data to the remote host.
        public NetworkStream GetStream()
        {
            ThrowIfDisposed();

            if (!Connected)
            {
                throw new InvalidOperationException(SR.net_notconnected);
            }

            if (_dataStream == null)
            {
                _dataStream = new NetworkStream(Client, true);
            }

            return(_dataStream);
        }
Пример #20
0
        User SingUp(NetworkStream?stream, Dictionary <string, object>?myObject)
        {
            var data = new Dictionary <string, object>();

            data["type"] = (int)Types.TYPE_Get_User;
            User user = SQLDataManager.CreateNewUser((string)myObject["name"], (string)myObject["email"], (string)myObject["pass"]);

            data["name"]  = (string)myObject["name"];
            data["uid"]   = user.uId;
            data["req"]   = 1;
            data["error"] = "null";

            Console.WriteLine($"BD New user: {(string)myObject["name"]} :: {user.uId}");
            sendDictionaryByJson(stream, data);
            return(user);
        }
Пример #21
0
        User LogIn(NetworkStream?stream, Dictionary <string, object>?myObject)
        {
            var data = new Dictionary <string, object>();

            data["type"] = (int)Types.TYPE_Get_User;
            User user = SQLDataManager.GetUserData((string)myObject["email"], (string)myObject["pass"]);

            if (user != null)
            {
                data["name"]  = user.name;
                data["uid"]   = user.uId;
                data["req"]   = 1;
                data["error"] = "null";
                Console.WriteLine($"BD login user: {user.name} :: {user.uId}");
                sendDictionaryByJson(stream, data);
            }
            return(user);
        }
Пример #22
0
        private void CloseConnection()
        {
            if (connection == null)
            {
                return;
            }

            try {
                networkStream?.Close(0);
            }
            catch (Exception) { }
            networkStream = null;

            try {
                connection.Close();
            }
            catch (Exception) { }
            connection = null;
        }
Пример #23
0
        public async Task <bool> SendAsync(string?content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return(false);
            }

            if (!Helpers.IsSocketConnected(Client?.Client))
            {
                return(false);
            }

            await SendSemaphore.WaitAsync().ConfigureAwait(false);

            CancellationTokenSource token  = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            NetworkStream?          stream = null;
            string?received = null;

            try {
                if (Client == null || !Client.Connected || !Client.GetStream().CanWrite)
                {
                    return(false);
                }

                stream = Client.GetStream();
                byte[] writeBuffer = Encoding.ASCII.GetBytes(content);
                stream.Write(writeBuffer, 0, writeBuffer.Length);
                await Task.Delay(100).ConfigureAwait(false);

                byte[] readBuffer = new byte[8000];
                while (stream.CanRead && stream.DataAvailable)
                {
                    stream.Read(readBuffer, 0, readBuffer.Length);
                }

                received = Encoding.ASCII.GetString(readBuffer);
                return(true);
            }
            finally {
                SendSemaphore.Release();
                stream?.Dispose();
            }
        }
Пример #24
0
        public FirmataTestFixture()
        {
            try
            {
                var loggerFactory = LoggerFactory.Create(builder =>
                {
                    builder.AddConsole().AddProvider(new DebuggerOutputLoggerProvider());
                });

                // Statically register our factory. Note that this must be done before instantiation of any class that wants to use logging.
                LogDispatcher.LoggerFactory = loggerFactory;
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.Connect(IPAddress.Loopback, 27016);
                _socket.NoDelay = true;
                _networkStream  = new NetworkStream(_socket, true);
                Board           = new ArduinoBoard(_networkStream);
                if (!(Board.FirmataVersion > new Version(1, 0)))
                {
                    // Actually not expecting to get here (but the above will throw a SocketException if the remote end is not there)
                    throw new NotSupportedException("Very old firmware found");
                }

                return;
            }
            catch (SocketException)
            {
                Console.WriteLine("Unable to connect to simulator, trying hardware...");
            }

            if (!ArduinoBoard.TryFindBoard(SerialPort.GetPortNames(), new List <int>()
            {
                115200
            }, out var board))
            {
                Board = null;
                return;
            }

            Board = board;
        }
Пример #25
0
        public void Start()
        {
            if (_isActive)
            {
                return;
            }
            _isActive = true;

            var tcpClient = TcpClient;

            tcpClient.ReceiveTimeout    = CoreConfiguration.P2PKeepAliveDuration * 2;
            tcpClient.SendTimeout       = CoreConfiguration.P2PKeepAliveDuration * 2;
            tcpClient.ReceiveBufferSize = CoreConfiguration.P2PReceiveBufferSize;
            tcpClient.SendBufferSize    = CoreConfiguration.P2PSendBufferSize;

            if (!tcpClient.Connected)
            {
                throw new Exception("Peer is not connected.");
            }

            NetworkStream = tcpClient.GetStream();

            try
            {
                HandleHandshakeRequest();

                var cancellationToken = _cancellationTokenSource.Token;

                _readPacketThread = new ReadPacketThread(this, cancellationToken);
                _readPacketThread.Start();

                _writePacketThread = new WritePacketThread(this, cancellationToken);
                _writePacketThread.Start();
            }
            catch (Exception)
            {
                // Something went wrong with the process, probably due to network error or packet issues.
                // TODO: Disconnect peer.
            }
        }
Пример #26
0
        public TdsStreamTcp(string serverName, int port, int timeoutSec)
        {
            _targetServer = serverName;

            var ts = new TimeSpan(0, 0, timeoutSec);

            _socket = Connect(serverName, port == -1 ? DefaultSqlServerPort : port, ts);

            if (_socket == null || !_socket.Connected)
            {
                throw new Exception($"Connection Failed to server'{serverName}:{port}'");
            }

            _socket.NoDelay = true;
            _tcpStream      = new NetworkStream(_socket, true);

            _sslOverTdsStream = new SslOverTdsStream(_tcpStream);
            _sslStream        = new SslStream(_sslOverTdsStream, true, ValidateServerCertificate, null);
            _stream           = _tcpStream;
            var serverSpn = GetSqlServerSpn(serverName, port);

            _sspi = new SspiHelper(serverSpn);
        }
Пример #27
0
        void CreateNewRoom(NetworkStream?stream, IPAddress address)
        {
            var data = new Dictionary <string, object>();

            data["type"] = (int)Types.TYPE_CreateRoomR;
            RoomServer roomServer = FindActiveRoom();

            if (roomServer == null)
            {
                try
                {
                    roomServer = new RoomServer(address, ++portroomnow)
                    {
                        Rules = new Rules(RedScore: 1)
                    };
                    Console.WriteLine($"Create new room{roomServer.PORT}");
                    rooms.Add(roomServer);
                    data["req"]   = 1;
                    data["port"]  = roomServer.PORT;
                    data["error"] = "null";
                }
                catch (Exception e)
                {
                    data["req"]   = 0;
                    data["error"] = e.Message;
                    Console.WriteLine($"\nError bd: {e.Message}\n{e.StackTrace}\n");
                }
            }
            else
            {
                Console.WriteLine($"Create new.. no we have free room {roomServer.PORT}");
                data["req"]   = 1;
                data["port"]  = roomServer.PORT;
                data["error"] = null;
            }
            sendDictionaryByJson(stream, data);
        }
Пример #28
0
        public void Start()
        {
            lock (lck)
            {
                exit = false;

                listener.Start();
                listener.BeginAcceptTcpClient(new AsyncCallback((result) =>
                {
                    client        = listener.EndAcceptTcpClient(result);
                    networkStream = client.GetStream();
                    Connected     = true;
                    streamReader  = new StreamReader(networkStream);

                    Task.Run(async() =>
                    {
                        while (true)
                        {
                            lock (lck)
                            {
                                if (exit)
                                {
                                    break;
                                }
                            }

                            if (!streamReader?.EndOfStream == true)
                            {
                                Received?.Invoke(this, streamReader !.ReadLine() !);
                            }

                            await Task.Delay(10);
                        }
                    });
                }), listener);
            }
        }
Пример #29
0
        private void Release(bool userRequestedDisconnect)
        {
            lock (netLock)
            {
                if (cancellationToken != null)
                {
                    cancellationToken.Dispose();
                    cancellationToken = null;
                }

                if (netWriter != null)
                {
                    netWriter.Dispose();
                    netWriter = null;
                }

                if (netReader != null)
                {
                    netReader.Dispose();
                    netReader = null;
                }

                if (netStream != null)
                {
                    netStream.Dispose();
                    netStream = null;
                }

                if (socket != null)
                {
                    socket.Dispose();
                    socket = null;
                }
            }

            Disconnected?.Invoke(this, new DisconnectedEventArgs(userRequestedDisconnect));
        }
Пример #30
0
        public FirmataTestFixture()
        {
            try
            {
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.Connect(IPAddress.Loopback, 27016);
                _socket.NoDelay = true;
                _networkStream  = new NetworkStream(_socket, true);
                Board           = new ArduinoBoard(_networkStream);
                if (!(Board.FirmataVersion > new Version(1, 0)))
                {
                    // Actually not expecting to get here (but the above will throw a SocketException if the remote end is not there)
                    throw new NotSupportedException("Very old firmware found");
                }

                Board.LogMessages += (x, y) => Console.WriteLine(x);

                return;
            }
            catch (SocketException)
            {
                Console.WriteLine("Unable to connect to simulator, trying hardware...");
            }

            if (!ArduinoBoard.TryFindBoard(SerialPort.GetPortNames(), new List <int>()
            {
                115200
            }, out var board))
            {
                Board = null;
                return;
            }

            Board              = board;
            Board.LogMessages += (x, y) => Console.WriteLine(x);
        }