コード例 #1
0
        private async Task Connect()
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            while (!socket.Connected)
            {
                try
                {
                    socket.Connect(this.host, this.port);
                }
                catch
                {
                    this.logger.LogWarning($"Connection to ExDB-Server ({this.host}:{this.port}) failed, trying again in 10 Seconds...");
                    await Task.Delay(10000).ConfigureAwait(false);
                }
            }

            this.logger.LogInformation("Connection to ExDB-Server established");

            this.connection = new Connection(SocketConnection.Create(socket), null, null, this.loggerFactory.CreateLogger <Connection>());
            this.connection.PacketReceived += this.ExDbPacketReceived;
            this.connection.Disconnected   += (sender, e) => Task.Run(async() => await this.Connect().ConfigureAwait(false));
            this.SendHello();
            await this.connection !.BeginReceive();
        }
コード例 #2
0
        public async Task ServerClientDoubleInverted_SslStream_PingPong()
        {
            Log.DebugLog();
            var tuple = CreateConnectedSocketPair();

            using (var client = tuple.Item1)
                using (var server = tuple.Item2)
                {
                    var clientPipe = SocketConnection.Create(client, PipeOptions, name: "socket client");
                    var serverPipe = SocketConnection.Create(server, PipeOptions, name: "socket server");

                    var serverStream = StreamConnection.GetDuplex(serverPipe, name: "stream server");
                    var serverSsl    = new SslStream(serverStream, false, IgnoreAllCertificateErrors, null, EncryptionPolicy.RequireEncryption);

                    var clientStream = StreamConnection.GetDuplex(clientPipe, name: "stream client");
                    var clientSsl    = new SslStream(clientStream, false, IgnoreAllCertificateErrors, null, EncryptionPolicy.RequireEncryption);

                    var serverAuth = serverSsl.AuthenticateAsServerAsync(SomeCertificate);
                    var clientAuth = clientSsl.AuthenticateAsClientAsync("somesite");

                    await serverAuth;
                    await clientAuth;

                    var serverRevert = StreamConnection.GetDuplex(serverSsl, PipeOptions, name: "revert server");
                    var clientRevert = StreamConnection.GetDuplex(clientSsl, PipeOptions, name: "revert client");



                    await PingPong(clientRevert, serverRevert, LoopCount);
                }
            Log.DebugLog("All good!");
        }
コード例 #3
0
        private void HandleNewSocket(Socket socket)
        {
            if (socket == null)
            {
                return;
            }

            var remoteEndPoint = socket.RemoteEndPoint;

            this.Log(l => l.DebugFormat($"Game Client connected, Address {remoteEndPoint}"));
            if (this.gameContext.PlayerList.Count >= this.gameContext.ServerConfiguration.MaximumPlayers)
            {
                this.Log(l => l.DebugFormat($"The server is full... disconnecting the game client {remoteEndPoint}"));

                // MAYBE TODO: wait until another player disconnects?
                socket.Dispose();
            }
            else
            {
                socket.NoDelay = true;
                var socketConnection = SocketConnection.Create(socket);
                var connection       = new Connection(socketConnection, new PipelinedDecryptor(socketConnection.Input), new PipelinedEncryptor(socketConnection.Output));
                var remotePlayer     = new RemotePlayer(this.gameContext, connection, new ClientVersion(this.endPoint.Client.Season, this.endPoint.Client.Episode, this.endPoint.Client.Language));
                this.OnPlayerConnected(remotePlayer);
                connection.Disconnected += (sender, e) => remotePlayer.Disconnect();

                // we don't want to await the call.
                connection.BeginReceive();
            }
        }
コード例 #4
0
        public void TestDisconnectOnInvalidHeaderReceived()
        {
            var server = new TcpListener(IPAddress.Any, 5000);

            server.Start();
            try
            {
                server.BeginAcceptSocket(
                    asyncResult =>
                {
                    var clientSocket = server.EndAcceptSocket(asyncResult);
                    var packet       = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF, 0, 0, 0, 0, 0, 0 };
                    clientSocket.BeginSend(packet, 0, packet.Length, SocketFlags.None, null, null);
                }, null);

                using var client = new TcpClient("127.0.0.1", 5000);
                var socketConnection = SocketConnection.Create(client.Client);
                var connection       = new Connection(socketConnection, new PipelinedDecryptor(socketConnection.Input), new PipelinedEncryptor(socketConnection.Output));

                connection.BeginReceive();

                Thread.Sleep(100);
                Assert.That(connection.Connected, Is.False);
            }
            finally
            {
                server.Stop();
            }
        }
コード例 #5
0
ファイル: MyClient.cs プロジェクト: tppApe/UfcppSample
        public static async Task <MyClient> CreateAsync(EndPoint endPoint)
        {
            var s = new Socket(SocketType.Stream, ProtocolType.Tcp);
            await s.ConnectAsync(endPoint);

            var p = SocketConnection.Create(s);

            var i = p.Input;
            var r = await i.ReadAsync();

            int read(ReadOnlySequence <byte> buffer)
            {
                var reader = new BufferReader <byte>(buffer);

                if (!reader.Read(out int x))
                {
                    throw new Exception();
                }
                return(x);
            }

            var id = read(r.Buffer);

            return(new MyClient(id, p));
        }
コード例 #6
0
        private void ClientConnected(object sender, ClientAcceptEventArgs e)
        {
            var clientConnection = e.AcceptedConnection;
            var serverSocket     = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            serverSocket.Connect(this.txtOtherServer.Text, (int)this.numRealGSPort.Value);
            var socketConnection = SocketConnection.Create(serverSocket);
            var encryptor        = new PipelinedXor32Encryptor(new PipelinedSimpleModulusEncryptor(socketConnection.Output, PipelinedSimpleModulusEncryptor.DefaultClientKey).Writer);
            var decryptor        = new PipelinedSimpleModulusDecryptor(socketConnection.Input, PipelinedSimpleModulusDecryptor.DefaultClientKey)
            {
                AcceptWrongBlockChecksum = true
            };
            var serverConnection = new Connection(socketConnection, decryptor, encryptor);
            var proxy            = new Proxy(clientConnection, serverConnection, this.InvokeByProxy);

            this.InvokeByProxy(new Action(() =>
            {
                this.proxiedConnections.Add(proxy);
                if (this.proxiedConnections.Count == 1)
                {
                    this.connectedClientsListBox.SelectedItem = proxy;
                    this.ConnectionSelected(this, EventArgs.Empty);
                }
            }));
        }
コード例 #7
0
 public void TestReceivePipelinedWithEncryption()
 {
     this.TestReceivePipelined(socket =>
     {
         var socketConnection = SocketConnection.Create(socket);
         return(new Connection(socketConnection, new PipelinedDecryptor(socketConnection.Input), new PipelinedEncryptor(socketConnection.Output)));
     });
 }
コード例 #8
0
 static void Main(string[] args)
 {
     using (var socket = new Socket(SocketType.Stream, ProtocolType.Tcp))
     {
         socket.Connect(IPAddress.Loopback, 3333);
         using (var sc = SocketConnection.Create(socket))
         {
             WorkWithSc(sc).GetAwaiter().GetResult();
         }
     }
 }
コード例 #9
0
        private IConnection CreateConnectionForSocket(Socket socket)
        {
            // Ensure that 'TCP.NODELAY' is configured on Windows
            SocketConnection.SetRecommendedClientOptions(socket);

            // Raw sockets themselves are not compatible with pipes
            var socketConnection = SocketConnection.Create(socket);
            var pipe             = new PipelinedSocket(
                socketConnection,
                this.Encryption?.Invoke(socketConnection.Output),
                this.Decryption?.Invoke(socketConnection.Input));

            return(new DuplexConnection(pipe, this.maxClientPacketSize));
        }
コード例 #10
0
        public async Task Basic_Pipelines_PingPong()
        {
            Log.DebugLog();
            var tuple = CreateConnectedSocketPair();

            using (var client = tuple.Item1)
                using (var server = tuple.Item2)
                {
                    var clientPipe = SocketConnection.Create(client, InlineReceive, InlineSend, name: "socket client");
                    var serverPipe = SocketConnection.Create(server, InlineReceive, InlineSend, name: "socket server");

                    await PingPong(clientPipe, serverPipe, LoopCount);
                }
            Log.DebugLog("All good!");
        }
コード例 #11
0
        public async Task ServerInverted_PingPong()
        {
            Log.DebugLog();
            var tuple = CreateConnectedSocketPair();

            using (var client = tuple.Item1)
                using (var server = tuple.Item2)
                {
                    var clientPipe = SocketConnection.Create(client, PipeOptions, name: "socket client");
                    var serverPipe = SocketConnection.Create(server, PipeOptions, name: "socket server");

                    var serverStream = StreamConnection.GetDuplex(serverPipe, name: "stream server");

                    await PingPong(clientPipe, serverStream, LoopCount);
                }
            Log.DebugLog("All good!");
        }
コード例 #12
0
ファイル: ClientListener.cs プロジェクト: zkings001/OpenMU
        private void AddClient(Socket socket)
        {
            var client     = new Client(new Connection(SocketConnection.Create(socket), null, null), this.connectServerSettings.Timeout, this.packetHandler, this.connectServerSettings.MaximumReceiveSize);
            var ipEndpoint = (IPEndPoint)socket.RemoteEndPoint;

            client.Address = ipEndpoint.Address;
            client.Port    = ipEndpoint.Port;
            client.Timeout = this.connectServerSettings.Timeout;

            lock (this.clientListLock)
            {
                this.Clients.Add(client);
            }

            client.Connection.Disconnected += (sender, e) => this.OnClientDisconnect(client);
            Logger.DebugFormat("Client connected: {0}, current client count: {1}", socket.RemoteEndPoint, this.Clients.Count);
            client.SendHello();
            client.Connection.BeginReceive();
        }
コード例 #13
0
        public async Task TestDisconnectOnInvalidHeaderSent()
        {
            IConnection connection = null;
            var         server     = new TcpListener(IPAddress.Any, 5000);

            server.Start();
            try
            {
                server.BeginAcceptSocket(
                    asyncResult =>
                {
                    var clientSocket     = server.EndAcceptSocket(asyncResult);
                    var socketConnection = SocketConnection.Create(clientSocket);
                    connection           = new Connection(socketConnection, new PipelinedDecryptor(socketConnection.Input), new PipelinedEncryptor(socketConnection.Output));
                }, null);

                using var client = new TcpClient("127.0.0.1", 5000);
                while (connection == null)
                {
                    Thread.Sleep(10);
                }

#pragma warning disable 4014
                connection.BeginReceive();
#pragma warning restore 4014

                var packet = new byte[22222];
                packet[0] = 0xDE;
                packet[1] = 0xAD;
                packet[2] = 0xBE;
                packet[3] = 0xAF;
                await connection.Output.WriteAsync(packet).ConfigureAwait(false);

                await Task.Delay(1000).ConfigureAwait(false);

                Assert.That(connection.Connected, Is.False);
            }
            finally
            {
                server.Stop();
            }
        }
コード例 #14
0
        public async Task Start(IPEndPoint localEP, DnsEndPoint remoteEP, string method, string?password, byte[]?key)
        {
            _listener.Start();

            while (true)
            {
                var socket = await _listener.AcceptSocketAsync();

                var conn = SocketConnection.Create(socket);

                foreach (var svc in _services)
                {
                    if (await svc.IsMyClient(conn))
                    {
                        // todo: save to list, so we can optionally close them
                        _ = RunService(svc, conn, localEP, remoteEP, method, password, key);
                    }
                }
            }
        }
コード例 #15
0
ファイル: ClientListener.cs プロジェクト: webdes27/OpenMU
        private void AddClient(Socket socket)
        {
            var connection = new Connection(SocketConnection.Create(socket), null, null, this.loggerFactory.CreateLogger <Connection>());
            var client     = new Client(connection, this.connectServerSettings.Timeout, this.packetHandler, this.connectServerSettings.MaximumReceiveSize, this.loggerFactory.CreateLogger <Client>());
            var ipEndpoint = socket.RemoteEndPoint as IPEndPoint;

            client.Address = ipEndpoint?.Address ?? IPAddress.None;
            client.Port    = ipEndpoint?.Port ?? 0;
            client.Timeout = this.connectServerSettings.Timeout;

            lock (this.clientListLock)
            {
                this.Clients.Add(client);
            }

            client.Connection.Disconnected += (sender, e) => this.OnClientDisconnect(client);
            this.logger.LogDebug("Client connected: {0}, current client count: {1}", socket.RemoteEndPoint, this.Clients.Count);
            client.SendHello();
            client.Connection.BeginReceive();
        }
コード例 #16
0
        public async Task Basic_Pipelines_Text_PingPong()
        {
            Log.DebugLog();
            var tuple = CreateConnectedSocketPair();

            using (var client = tuple.Item1)
                using (var server = tuple.Item2)
                {
                    var clientPipe = SocketConnection.Create(client, InlineReceive, InlineSend, name: "socket client");
                    var serverPipe = SocketConnection.Create(server, InlineReceive, InlineSend, name: "socket server");

                    var enc = Encoding.UTF8;
                    await PingPong(
                        PipeTextReader.Create(clientPipe.Input, enc),
                        PipeTextWriter.Create(clientPipe.Output, enc),
                        PipeTextReader.Create(serverPipe.Input, enc),
                        PipeTextWriter.Create(serverPipe.Output, enc),
                        LoopCount);
                }
            Log.DebugLog("All good!");
        }
コード例 #17
0
        private void HandleNewSocket(Socket socket)
        {
            if (socket == null)
            {
                return;
            }

            var remoteEndPoint = socket.RemoteEndPoint;

            this.Log(l => l.DebugFormat($"Game Client connected, Address {remoteEndPoint}"));
            if (this.gameContext.PlayerList.Count >= this.gameContext.ServerConfiguration.MaximumPlayers)
            {
                this.Log(l => l.DebugFormat($"The server is full... disconnecting the game client {remoteEndPoint}"));

                // MAYBE TODO: wait until another player disconnects?
                socket.Dispose();
            }
            else
            {
                socket.NoDelay = true;
                var socketConnection        = SocketConnection.Create(socket);
                var clientVersion           = new ClientVersion(this.endPoint.Client.Season, this.endPoint.Client.Episode, this.endPoint.Client.Language);
                var encryptionFactoryPlugIn = this.gameContext.PlugInManager.GetStrategy <ClientVersion, INetworkEncryptionFactoryPlugIn>(clientVersion)
                                              ?? this.gameContext.PlugInManager.GetStrategy <ClientVersion, INetworkEncryptionFactoryPlugIn>(default);
コード例 #18
0
        private IConnection CreateConnection(Socket clientSocket)
        {
            var socketConnection = SocketConnection.Create(clientSocket);

            return(new Connection(socketConnection, this.decryptorCreator(socketConnection.Input), this.encryptorCreator(socketConnection.Output)));
        }
コード例 #19
0
 public void TestReceivePipelined()
 {
     this.TestReceivePipelined(socket => new Connection(SocketConnection.Create(socket), null, null));
 }
コード例 #20
0
        private IConnection CreateConnection(Socket clientSocket)
        {
            var socketConnection = SocketConnection.Create(clientSocket);

            return(new Connection(socketConnection, this.CreateDecryptor(socketConnection.Input), this.CreateEncryptor(socketConnection.Output), this.loggerFactory.CreateLogger <Connection>()));
        }
コード例 #21
0
 public SocketDuplexMessageStream(SocketProviderAsync provider)
     : this(async(token) => SocketConnection.Create(await provider(token).ConfigureAwait(false)))
 {
 }