Example #1
0
    //생성자.
    public NetworkController(string hostAddress, bool isHost) {
        DebugWriterSetup();

        isSynchronized = false;
		m_hostType = isHost? HostType.Server : HostType.Client;

        GameObject nObj = GameObject.Find("Network");
        m_transport = nObj.GetComponent<TransportUDP>();
		// 동일 단말에서 실행할 수 있게 포트 번호를 변경합니다.
		// 다른 단말에서 실행할 경우 포트 번호가 같은 것을 사용합니다.
		int listeningPort = isHost? NetConfig.GAME_PORT : NetConfig.GAME_PORT + 1;
		m_transport.StartServer(listeningPort);
		// 동일 단말에서 실행할 수 있게 포트 번호를 변경합니다.
		// 다른 단말에서 실행할 경우 포트 번호가 같은 것을 사용합니다.
		int remotePort = isHost? NetConfig.GAME_PORT + 1 : NetConfig.GAME_PORT;
		m_transport.Connect(hostAddress, remotePort);

		m_transport.RegisterEventHandler(OnEventHandling);

        GameObject iObj = GameObject.Find("InputManager");
        m_inputManager = iObj.GetComponent<InputManager>();

        for (int i = 0; i < inputBuffer.Length; ++i) {
            inputBuffer[i] = new List<MouseData>();
        }
    }
Example #2
0
            public void ClientStopsReconnectingAfterDisconnectTimeout(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: 1, disconnectTimeout: 2);
                    var connection = new Client.Hubs.HubConnection(host.Url);
                    var reconnectWh = new ManualResetEventSlim();
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Reconnecting += () =>
                    {
                        reconnectWh.Set();
                        Assert.Equal(ConnectionState.Reconnecting, connection.State);
                    };

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                        Assert.Equal(ConnectionState.Disconnected, connection.State);
                    };

                    connection.Start(host.Transport).Wait();
                    host.Shutdown();

                    Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(5)));
                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(5)));
                }
            }
Example #3
0
            public void ThrownWebExceptionShouldBeUnwrapped(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection = new Client.Connection(host.Url + "/ErrorsAreFun");

                    // Expecting 404
                    var aggEx = Assert.Throws<AggregateException>(() => connection.Start(host.Transport).Wait());

                    connection.Stop();

                    using (var ser = aggEx.GetError())
                    {
                        if (hostType == HostType.IISExpress)
                        {
                            Assert.Equal(System.Net.HttpStatusCode.InternalServerError, ser.StatusCode);
                        }
                        else
                        {
                            Assert.Equal(System.Net.HttpStatusCode.NotFound, ser.StatusCode);
                        }

                        Assert.NotNull(ser.ResponseBody);
                        Assert.NotNull(ser.Exception);
                    }
                }
            }
Example #4
0
        public void InstanceContext(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy<InstanceContextStartup>(hostType);
                string[] urls = new string[] { applicationUrl, applicationUrl + "/one", applicationUrl + "/two" };

                bool failed = false;

                foreach (string url in urls)
                {
                    string previousResponse = null;
                    for (int count = 0; count < 3; count++)
                    {
                        string currentResponse = HttpClientUtility.GetResponseTextFromUrl(url);

                        if (!currentResponse.Contains("SUCCESS") || (previousResponse != null && currentResponse != previousResponse))
                        {
                            failed = true;
                        }

                        previousResponse = currentResponse;
                    }
                }

                Assert.True(!failed, "At least one of the instance contexts is not correct");
            }
        }
        public void ReconnectionSuccesfulTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new ManualResetEventSlim(false);
                host.Initialize(keepAlive: null, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                using (connection)
                {
                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2));

                    connection.Reconnected += () =>
                    {
                        mre.Set();
                    };

                    connection.Start(host.Transport).Wait();

                    // Assert
                    Assert.True(mre.Wait(TimeSpan.FromSeconds(10)));

                    // Clean-up
                    mre.Dispose();
                }
            }
        }
Example #6
0
        public void EndToEndTest(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize();

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy proxy = hubConnection.CreateHubProxy("ChatHub");
                var wh = new ManualResetEvent(false);

                proxy.On("addMessage", data =>
                {
                    Assert.Equal("hello", data);
                    wh.Set();
                });

                hubConnection.Start(host.Transport).Wait();

                proxy.InvokeWithTimeout("Send", "hello");

                Assert.True(wh.WaitOne(TimeSpan.FromSeconds(10)));

                hubConnection.Stop();
            }
        }
Example #7
0
    //클라이언트에서 사용할 때.
    public NetworkController(string serverAddress) {
        m_hostType = HostType.Client;

        GameObject nObj = GameObject.Find("Network");
		m_network = nObj.GetComponent<TransportTCP>();
        m_network.Connect(serverAddress, USE_PORT);
    }
Example #8
0
        public async Task CanInvokeMethodsAndReceiveMessagesFromValidTypedHub(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                using (var connection = CreateHubConnection(host))
                {
                    var hub = connection.CreateHubProxy("ValidTypedHub");
                    var echoTcs = new TaskCompletionSource<string>();
                    var pingWh = new ManualResetEventSlim();

                    hub.On<string>("Echo", message => echoTcs.TrySetResult(message));
                    hub.On("Ping", pingWh.Set);

                    await connection.Start(host.TransportFactory());

                    hub.InvokeWithTimeout("Echo", "arbitrary message");
                    Assert.True(echoTcs.Task.Wait(TimeSpan.FromSeconds(10)));
                    Assert.Equal("arbitrary message", echoTcs.Task.Result);

                    hub.InvokeWithTimeout("Ping");
                    Assert.True(pingWh.Wait(TimeSpan.FromSeconds(10)));
                }
            }
        }
Example #9
0
        public void OwinCallCancelled(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var serverInstance = new NotificationServer();
                serverInstance.StartNotificationService();

                string applicationUrl = deployer.Deploy(hostType, Configuration);

                try
                {
                    Trace.WriteLine(string.Format("Making a request to url : ", applicationUrl));
                    HttpClient httpClient = new HttpClient();
                    Task<HttpResponseMessage> response = httpClient.GetAsync(applicationUrl);
                    response.Wait(1 * 1000);
                    httpClient.CancelPendingRequests();
                    bool receivedNotification = serverInstance.NotificationReceived.WaitOne(20 * 1000);
                    Assert.True(receivedNotification, "CallCancelled CancellationToken was not issued on cancelling the call");
                }
                finally
                {
                    serverInstance.Dispose();
                }
            }
        }
Example #10
0
        public void ReconnectRequestPathEndsInReconnect(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var tcs = new TaskCompletionSource<bool>();
                var receivedMessage = false;

                host.Initialize(keepAlive: null,
                                connectionTimeout: 2,
                                disconnectTimeout: 6);

                var connection = CreateConnection(host, "/examine-reconnect");

                connection.Received += (reconnectEndsPath) =>
                {
                    if (!receivedMessage)
                    {
                        tcs.TrySetResult(reconnectEndsPath == "True");
                        receivedMessage = true;
                    }
                };

                connection.Start(host.Transport).Wait();

                // Wait for reconnect
                Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(10)));
                Assert.True(tcs.Task.Result);

                // Clean-up
                connection.Stop();
            }
        }
Example #11
0
        public void ApplicationPoolStop(HostType hostType)
        {
            var serverInstance = new NotificationServer();
            serverInstance.StartNotificationService();
            try
            {
                using (ApplicationDeployer deployer = new ApplicationDeployer())
                {
                    string applicationUrl = deployer.Deploy(hostType, Configuration);
                    Assert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl) == "SUCCESS");

                    if (hostType == HostType.IIS)
                    {
                        string webConfig = deployer.GetWebConfigPath();
                        string webConfigContent = File.ReadAllText(webConfig);
                        File.WriteAllText(webConfig, webConfigContent);
                    }
                }

                bool receivedNotification = serverInstance.NotificationReceived.WaitOne(20 * 1000);
                Assert.True(receivedNotification, "Cancellation token was not issued on closing host");
            }
            finally
            {
                serverInstance.Dispose();
            }
        }
Example #12
0
        public void CancelledGenericTask(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize();
                var connection = new Client.Hubs.HubConnection(host.Url);
                var tcs = new TaskCompletionSource<object>();

                var hub = connection.CreateHubProxy("demo");
                connection.Start(host.Transport).Wait();

                hub.Invoke("CancelledGenericTask").ContinueWith(tcs);

                try
                {
                    tcs.Task.Wait(TimeSpan.FromSeconds(10));
                    Assert.True(false, "Didn't fault");
                }
                catch (Exception)
                {

                }

                connection.Stop();
            }
        }
Example #13
0
 public void Remove(HostType hashCode)
 {
     if (this.commandHosts.ContainsKey(hashCode))
     {
         this.commandHosts.Remove(hashCode);
     }
 }
Example #14
0
        public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    connection.Start(host.Transport).Wait();

                    // The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect.
                    ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1);

                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Example #15
0
        public void AddingToMultipleGroups(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize();
                int max = 10;

                var countDown = new CountDownRange<int>(Enumerable.Range(0, max));
                var connection = new Client.Hubs.HubConnection(host.Url);
                var proxy = connection.CreateHubProxy("MultGroupHub");

                proxy.On<User>("onRoomJoin", user =>
                {
                    Assert.True(countDown.Mark(user.Index));
                });

                connection.Start(host.Transport).Wait();

                for (int i = 0; i < max; i++)
                {
                    var user = new User { Index = i, Name = "tester", Room = "test" + i };
                    proxy.InvokeWithTimeout("login", user);
                    proxy.InvokeWithTimeout("joinRoom", user);
                }

                Assert.True(countDown.Wait(TimeSpan.FromSeconds(30)), "Didn't receive " + max + " messages. Got " + (max - countDown.Count) + " missed " + String.Join(",", countDown.Left.Select(i => i.ToString())));

                connection.Stop();
            }
        }
Example #16
0
        public BaseSocketConnectionHost(HostType hostType, CallbackThreadType callbackThreadtype, ISocketService socketService, DelimiterType delimiterType, byte[] delimiter, int socketBufferSize, int messageBufferSize, int idleCheckInterval, int idleTimeOutValue)
        {
            context = new SocketProviderContext
            {
                Active = false,
                SyncActive = new object(),
                SocketCreators = new List<BaseSocketConnectionCreator>(),
                SocketConnections = new Dictionary<long, BaseSocketConnection>(),
                BufferManager = BufferManager.CreateBufferManager(0, messageBufferSize),
                SocketService = socketService,
                IdleCheckInterval = idleCheckInterval,
                IdleTimeOutValue = idleTimeOutValue,
                CallbackThreadType = callbackThreadtype,
                DelimiterType = delimiterType,
                Delimiter = delimiter,
                DelimiterEncrypt = new byte[] { 0xFE, 0xDC, 0xBA, 0x98, 0xBA, 0xDC, 0xFE },
                MessageBufferSize = messageBufferSize,
                SocketBufferSize = socketBufferSize,
                HostType = hostType
            };

            fSocketConnectionsSync = new ReaderWriterLockSlim();
            fWaitCreatorsDisposing = new ManualResetEvent(false);
            fWaitConnectionsDisposing = new ManualResetEvent(false);
            fWaitThreadsDisposing = new ManualResetEvent(false);
        }
Example #17
0
 public AccountTypeDB GetAccountTypeByHostType(HostType hostType)
 {
     DBManager db = new DBManager();
     string accountTypeName = AccountTypeDB.FromTypeCodeToString(hostType);
     var accountType = db.GetAccountTypeByName(accountTypeName);
     return accountType;
 }
Example #18
0
        public void Static_DirectoryBrowserDefaults(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, DirectoryBrowserDefaultsConfiguration);

                HttpResponseMessage response = null;

                //1. Check directory browsing enabled at application level
                var responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl, out response);
                Assert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                Assert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                Assert.True(responseText.Contains("RequirementFiles/"));

                //2. Check directory browsing @RequirementFiles with a ending '/'
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "RequirementFiles/", out response);
                Assert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                Assert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                Assert.True(responseText.Contains("Dir1/") && responseText.Contains("Dir2/") && responseText.Contains("Dir3/"), "Directories Dir1, Dir2, Dir3 not found");

                //2. Check directory browsing @RequirementFiles with request path not ending '/'
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "RequirementFiles", out response);
                Assert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                Assert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                Assert.True(responseText.Contains("Dir1/") && responseText.Contains("Dir2/") && responseText.Contains("Dir3/"), "Directories Dir1, Dir2, Dir3 not found");
            }
        }
Example #19
0
        public void Static_ValidIfModifiedSince(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, ValidModifiedSinceConfiguration);
                var httpClient = new HttpClient() { BaseAddress = new Uri(applicationUrl) };
                var fileContent = File.ReadAllBytes(@"RequirementFiles/Dir1/RangeRequest.txt");

                var response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);

                //Modified since = lastmodified. Expect a 304
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified;
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.NotModified, response.StatusCode);

                //Modified since > lastmodified. Expect a 304
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified.Value.AddMinutes(12);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.NotModified, response.StatusCode);

                //Modified since < lastmodified. Expect an OK. 
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified.Value.Subtract(new TimeSpan(10 * 1000));
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //Modified since is an invalid date string. Expect an OK. 
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("If-Modified-Since", "InvalidDate");
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
            }
        }
Example #20
0
        public async Task ReconnectionSuccesfulTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new AsyncManualResetEvent(false);
                host.Initialize(keepAlive: null, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                if (transportType == TransportType.LongPolling)
                {
                    ((Client.Transports.LongPollingTransport)host.Transport).ReconnectDelay = TimeSpan.Zero;
                }

                using (connection)
                {
                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2));

                    connection.Reconnected += () =>
                    {
                        mre.Set();
                    };

                    await connection.Start(host.Transport);

                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10)));

                    // Clean-up
                    mre.Dispose();
                }
            }
        }
Example #21
0
        protected ITestHost CreateHost(HostType hostType, TransportType transportType)
        {
            ITestHost host = null;

            switch (hostType)
            {
                case HostType.IISExpress:
                    host = new IISExpressTestHost();
                    host.TransportFactory = () => CreateTransport(transportType);
                    host.Transport = host.TransportFactory();
                    break;
                case HostType.Memory:
                    var mh = new MemoryHost();
                    host = new MemoryTestHost(mh);
                    host.TransportFactory = () => CreateTransport(transportType, mh);
                    host.Transport = host.TransportFactory();
                    break;
                case HostType.Owin:
                    host = new OwinTestHost();
                    host.TransportFactory = () => CreateTransport(transportType);
                    host.Transport = host.TransportFactory();
                    break;
                default:
                    break;
            }

            return host;
        }
        public async Task TransportTimesOutIfNoInitMessage(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            var mre = new AsyncManualResetEvent();

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(transportConnectTimeout: 1, messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host, "/no-init");

                IHubProxy proxy = hubConnection.CreateHubProxy("DelayedOnConnectedHub");

                using (hubConnection)
                {
                    try
                    {
                        await hubConnection.Start(host.Transport);
                    }
                    catch
                    {
                        mre.Set();
                    }

                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10)));
                }
            }
        }
Example #23
0
        public void ReconnectExceedingReconnectWindowDisconnectsWithFastBeatInterval(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            // Test cannot be async because if we do host.ShutDown() after an await the connection stops.

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(keepAlive: 9, messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    SetReconnectDelay(host.Transport, TimeSpan.FromSeconds(15));

                    connection.Start(host.Transport).Wait();                    

                    // Without this the connection start and reconnect can race with eachother resulting in a deadlock.
                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    // Set reconnect window to zero so the second we attempt to reconnect we can ensure that the reconnect window is verified.
                    ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(0);

                    host.Shutdown();

                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Example #24
0
        public void Static_ContentTypes(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, ContentTypesConfiguration);
                var httpClient = new HttpClient() { BaseAddress = new Uri(applicationUrl) };

                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleAVI.avi", "video/x-msvideo");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleC.c", "text/plain");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleCHM.chm", "application/octet-stream");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleCpp.cpp", "text/plain");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleCss.CSS", "text/css");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleCSV.csV", "application/octet-stream");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleCUR.cur", "application/octet-stream");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleDisco.disco", "text/xml");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\Sampledoc.doc", "application/msword");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\Sampledocx.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleHTM.htm", "text/html");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\Samplehtml.html", "text/html");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\Sampleico.ico", "image/x-icon");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleJPEG.jpg", "image/jpeg");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SampleJPG.jpg", "image/jpeg");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\ContentTypes\SamplePNG.png", "image/png");
                DownloadAndCompareFiles(httpClient, @"RequirementFiles\Dir1\EmptyFile.txt", "text/plain");

                //Unknown MIME types should not be served by default
                var response = httpClient.GetAsync(@"RequirementFiles\ContentTypes\Unknown.Unknown").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.NotFound, response.StatusCode);
            }
        }
Example #25
0
        public void SuccessiveTimeoutTest(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new ManualResetEventSlim(false);
                host.Initialize(keepAlive: null);
                var connection = CreateConnection(host, "/my-reconnect");

                ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2));

                connection.Reconnected += () =>
                {
                    mre.Set();
                };

                connection.Start(host.Transport).Wait();

                // Assert that Reconnected is called
                Assert.True(mre.Wait(TimeSpan.FromSeconds(10)));

                // Assert that Reconnected is called again
                mre.Reset();
                Assert.True(mre.Wait(TimeSpan.FromSeconds(10)));

                // Clean-up
                mre.Dispose();
                connection.Stop();
            }
        }
        public async Task SuccessiveTimeoutTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new AsyncManualResetEvent(false);
                host.Initialize(keepAlive: 5, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                using (connection)
                {
                    connection.Reconnected += () =>
                    {
                        mre.Set();
                    };

                    await connection.Start(host.Transport);

                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromMilliseconds(300));

                    // Assert that Reconnected is called
                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(15)));

                    // Assert that Reconnected is called again
                    mre.Reset();
                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(15)));

                    // Clean-up
                    mre.Dispose();
                }
            }
        }
            public void GroupsReceiveMessages(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection = CreateConnection(host, "/groups");
                    var list = new List<string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.SendWithTimeout(new { type = 1, group = "test" });

                    // Sent a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "hello to group test" });

                    // Leave the group
                    connection.SendWithTimeout(new { type = 2, group = "test" });

                    // Send a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "goodbye to group test" });

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(1, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                }
            }
        public void Security_ReturnUrlAndSecureCookie(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, ReturnUrlAndSecureCookieConfiguration);
                string secureServerUri = new UriBuilder(applicationUrl) { Scheme = Uri.UriSchemeHttps }.Uri.AbsoluteUri;

                HttpClientHandler handler = new HttpClientHandler();
                HttpClient httpClient = new HttpClient(handler);

                // Unauthenticated request - verify Redirect url
                HttpResponseMessage response = httpClient.GetAsync(applicationUrl).Result;
                CookiesCommon.IsRedirectedToCookiesLogin(response.RequestMessage.RequestUri, applicationUrl, "Unauthenticated requests not automatically redirected to login page", "MyRedirectUrl");

                var validCookieCredentials = new FormUrlEncodedContent(new kvp[] { new kvp("username", "test"), new kvp("password", "test") });
                response = httpClient.PostAsync(response.RequestMessage.RequestUri, validCookieCredentials).Result;
                response.EnsureSuccessStatusCode();

                //Verify cookie sent
                Assert.False(handler.CookieContainer.Count != 1, "Forms auth cookie not received automatically after successful login");
                Cookie loginCookie = handler.CookieContainer.GetCookies(new Uri(secureServerUri))[0];

                Assert.Equal(loginCookie.Secure, true);
            }
        }
Example #29
0
        public void ConnectionErrorCapturesExceptionsThrownInClientHubMethod(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                var wh = new ManualResetEventSlim();
                Exception thrown = new Exception(),
                          caught = null;

                host.Initialize();

                var connection = CreateHubConnection(host);
                var proxy = connection.CreateHubProxy("ChatHub");

                proxy.On("addMessage", () =>
                {
                    throw thrown;
                });

                connection.Error += e =>
                {
                    caught = e;
                    wh.Set();
                };

                connection.Start(host.Transport).Wait();
                proxy.Invoke("Send", "");

                Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
                Assert.Equal(thrown, caught);
            }
        }
Example #30
0
    //서버에서 사용할 때.
    public NetworkController() {
        m_hostType = HostType.Server;

        GameObject nObj = GameObject.Find("Network");
        m_network = nObj.GetComponent<TransportTCP>();
        m_network.StartServer(USE_PORT, 1);
    }
            // [InlineData(HostType.IISExpress, TransportType.Websockets)]
            public void GroupsReceiveMessages(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection = CreateConnection(host, "/groups");
                    var list       = new List <string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.SendWithTimeout(new { type = 1, group = "test" });

                    // Sent a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "hello to group test" });

                    // Leave the group
                    connection.SendWithTimeout(new { type = 2, group = "test" });

                    for (int i = 0; i < 10; i++)
                    {
                        // Send a message
                        connection.SendWithTimeout(new { type = 3, group = "test", message = "goodbye to group test" });
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(1, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                }
            }
Example #32
0
        public void RequestHeadersSetCorrectly(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var tcs = new TaskCompletionSource <object>();
                host.Initialize();
                var connection = CreateConnection(host, "/examine-request");

                connection.Received += (arg) =>
                {
                    JObject headers = JsonConvert.DeserializeObject <JObject>(arg);
                    if (transportType != TransportType.Websockets)
                    {
                        Assert.Equal("referer", (string)headers["refererHeader"]);
                    }
                    Assert.Equal("test-header", (string)headers["testHeader"]);
                    tcs.TrySetResult(null);
                };

                connection.Error += e => tcs.TrySetException(e);

                connection.Headers.Add("test-header", "test-header");
                if (transportType != TransportType.Websockets)
                {
                    connection.Headers.Add(System.Net.HttpRequestHeader.Referer.ToString(), "referer");
                }

                connection.Start(host.Transport).Wait();
                connection.Send("Hello");

                // Assert
                Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(10)));

                // Clean-up
                connection.Stop();
            }
        }
Example #33
0
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.IISExpress, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.LongPolling, MessageBusType.Default)]
        public async Task ConnectionFunctionsCorrectlyAfterCallingStartMutlipleTimes(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                using (var connection = CreateConnection(host, "/echo"))
                {
                    var tcs = new TaskCompletionSource <object>();
                    connection.Received += _ => tcs.TrySetResult(null);

                    // We're purposely calling Start() twice here
                    await connection.Start(host.TransportFactory()).OrTimeout();

                    await connection.Start(host.TransportFactory()).OrTimeout();

                    await connection.Send("test").OrTimeout();

                    // Wait for message to be received
                    await tcs.Task.OrTimeout(TimeSpan.FromSeconds(10));
                }
            }
        }
Example #34
0
        public void DynamicInvokeTest(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize();
                var connection = new Client.Hubs.HubConnection(host.Url);

                string callback = @"!!!|\CallMeBack,,,!!!";

                var hub = connection.CreateHubProxy("demo");

                var wh = new ManualResetEventSlim(false);

                hub.On(callback, () => wh.Set());

                connection.Start(host.Transport).Wait();

                hub.InvokeWithTimeout("DynamicInvoke", callback);

                Assert.True(wh.Wait(TimeSpan.FromSeconds(10)));
                connection.Stop();
            }
        }
Example #35
0
        public void HubNamesAreNotCaseSensitive(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize();

                var       hubConnection = new HubConnection(host.Url);
                IHubProxy proxy         = hubConnection.CreateHubProxy("chatHub");
                var       wh            = new ManualResetEvent(false);

                proxy.On("addMessage", data =>
                {
                    Assert.Equal("hello", data);
                    wh.Set();
                });

                hubConnection.Start(host.Transport).Wait();

                proxy.InvokeWithTimeout("Send", "hello");

                Assert.True(wh.WaitOne(TimeSpan.FromSeconds(5)));
            }
        }
Example #36
0
        public async Task CannotInvokeMethodsAndReceiveMessagesFromInvalidTypedHub(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                using (var connection = CreateHubConnection(host))
                {
                    var hub = connection.CreateHubProxy("InvalidTypedHub");
                    var tcs = new TaskCompletionSource <string>();

                    await connection.Start(host.TransportFactory());

                    var ex = Assert.Throws <AggregateException>(() => hub.InvokeWithTimeout("Echo", "arbitrary message"));
                    Assert.Equal(1, ex.InnerExceptions.Count);
                    Assert.IsType <InvalidOperationException>(ex.InnerExceptions[0]);

                    ex = Assert.Throws <AggregateException>(() => hub.InvokeWithTimeout("Ping"));
                    Assert.Equal(1, ex.InnerExceptions.Count);
                    Assert.IsType <InvalidOperationException>(ex.InnerExceptions[0]);
                }
            }
        }
Example #37
0
            public async Task AwaitingOnFailedStartAndThenStoppingDoesntHang(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);
                    var badConnection = CreateConnection(host, "/ErrorsAreFun");

                    var startTime = DateTime.UtcNow;

                    try
                    {
                        await badConnection.Start(HostedTestFactory.CreateTransport(transportType));
                    }
                    catch
                    {
                        badConnection.Stop();
                        Assert.True(DateTime.UtcNow - startTime < TimeSpan.FromSeconds(10));
                        return;
                    }

                    Assert.True(false, "An exception should have been thrown.");
                }
            }
Example #38
0
 internal DeployedCodePackage(
     string codePackageName,
     string codePackageVersion,
     CodePackageEntryPoint setupEntryPoint,
     string serviceManifestName,
     string servicePackageActivationId,
     long runFrequencyInterval,
     HostType hostType,
     HostIsolationMode hostIsolationMode,
     DeploymentStatus deployedCodePackageStatus,
     CodePackageEntryPoint entryPoint)
 {
     this.CodePackageName            = codePackageName;
     this.CodePackageVersion         = codePackageVersion;
     this.SetupEntryPoint            = setupEntryPoint;
     this.ServiceManifestName        = serviceManifestName;
     this.ServicePackageActivationId = servicePackageActivationId;
     this.RunFrequencyInterval       = runFrequencyInterval;
     this.HostType                  = hostType;
     this.HostIsolationMode         = hostIsolationMode;
     this.DeployedCodePackageStatus = deployedCodePackageStatus;
     this.EntryPoint                = entryPoint;
 }
Example #39
0
        protected ITestHost CreateHost(HostType hostType, TransportType transportType)
        {
            ITestHost host = null;

            switch (hostType)
            {
            case HostType.IISExpress:
                host           = new IISExpressTestHost();
                host.Transport = CreateTransport(transportType);
                break;

            case HostType.Memory:
                var mh = new MemoryHost();
                host           = new MemoryTestHost(mh);
                host.Transport = CreateTransport(transportType, mh);
                break;

            default:
                break;
            }

            return(host);
        }
Example #40
0
            public void ClientStaysReconnectedAfterDisconnectTimeout(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: null,
                                    connectionTimeout: 2,
                                    disconnectTimeout: 8, // 8s because the default heartbeat time span is 5s
                                    messageBusType: messageBusType);

                    var connection = CreateHubConnection(host, "/force-lp-reconnect");

                    using (connection)
                    {
                        var reconnectingWh = new ManualResetEventSlim();
                        var reconnectedWh  = new ManualResetEventSlim();

                        connection.Reconnecting += () =>
                        {
                            reconnectingWh.Set();
                            Assert.Equal(ConnectionState.Reconnecting, connection.State);
                        };

                        connection.Reconnected += () =>
                        {
                            reconnectedWh.Set();
                            Assert.Equal(ConnectionState.Connected, connection.State);
                        };

                        connection.Start(host.Transport).Wait();

                        Assert.True(reconnectingWh.Wait(TimeSpan.FromSeconds(30)));
                        Assert.True(reconnectedWh.Wait(TimeSpan.FromSeconds(30)));
                        Thread.Sleep(TimeSpan.FromSeconds(15));
                        Assert.NotEqual(ConnectionState.Disconnected, connection.State);
                    }
                }
            }
Example #41
0
        private async Task PullImageOntoHost(DockerImage image, HostType hostType)
        {
            Guard.Against.Null(image, nameof(image));
            Guard.Against.Null(hostType, nameof(hostType));

            var parameters = new ImagesCreateParameters
            {
                FromImage = image.ImageName,
                Tag       = image.ImageTag
            };

            var config = new AuthConfig();

            if (image.PrivateRepository)
            {
                config.Username      = image.PrivateRepositoryUsername;
                config.Password      = image.PrivateRepositoryPassword;
                config.ServerAddress = image.PrivateRepositoryHost;
            }

            var progress = new Progress <JSONMessage>(stats => Console.WriteLine(stats.Status));

            //Actually Pulldown image

            switch (hostType)
            {
            case HostType.Application:
                await _dockerAppClient.Images.CreateImageAsync(parameters, config, progress, CancellationToken.None);

                break;

            case HostType.Benchmark:
                await _dockerBenchmarkClient.Images.CreateImageAsync(parameters, config, progress, CancellationToken.None);

                break;
            }
        }
Example #42
0
            public void GroupsDontRejoinByDefault(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: null,
                                    connectionTimeout: 2,
                                    hearbeatInterval: 2);

                    var connection = new Client.Connection(host.Url + "/groups");
                    var list       = new List <string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.SendWithTimeout(new { type = 1, group = "test" });

                    // Sent a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "hello to group test" });

                    // Force Reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    // Send a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "goodbye to group test" });

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(1, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                }
            }
Example #43
0
        public void Security_HttpCookieOnlyAndCookiePath(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl       = deployer.Deploy(hostType, HttpCookieOnlyAndCookiePathConfiguration);
                string passiveAuthLoginPage = applicationUrl + "Auth/PassiveAuthLogin";
                string homePath             = applicationUrl + "Auth/Home";
                string logoutPath           = applicationUrl + string.Format("Auth/Logout?ReturnUrl={0}", new Uri(homePath).AbsolutePath);

                var handler    = new HttpClientHandler();
                var httpClient = new HttpClient(handler);

                var response = httpClient.GetAsync(passiveAuthLoginPage).Result;
                CookiesCommon.IsRedirectedToCookiesLogin(response.RequestMessage.RequestUri, passiveAuthLoginPage, "Unauthenticated requests not automatically redirected to login page");
                var validCookieCredentials = new FormUrlEncodedContent(new kvp[] { new kvp("username", "test"), new kvp("password", "test") });
                response = httpClient.PostAsync(response.RequestMessage.RequestUri, validCookieCredentials).Result;

                //Verify cookie sent
                Assert.Equal(2, handler.CookieContainer.Count);
                CookieCollection cookies           = handler.CookieContainer.GetCookies(new Uri(applicationUrl + "Auth"));
                Cookie           applicationCookie = cookies[CookieAuthenticationDefaults.CookiePrefix + "Application"];
                Cookie           temporaryCookie   = cookies["TemporaryCookie"];
                Assert.NotNull(applicationCookie);
                Assert.NotNull(temporaryCookie);

                Assert.True(applicationCookie.HttpOnly);
                Assert.Equal("/", applicationCookie.Path);
                Assert.False(temporaryCookie.HttpOnly);
                Assert.Equal(temporaryCookie.Path, new Uri(applicationUrl).AbsolutePath + "Auth");
                Assert.Equal(applicationUrl, response.RequestMessage.RequestUri.AbsoluteUri);

                //Logout the client
                response = httpClient.GetAsync(logoutPath).Result;
                Assert.True(handler.CookieContainer.Count == 0, "Cookie is not cleared on logout");
                Assert.Equal(homePath, response.RequestMessage.RequestUri.AbsoluteUri);
            }
        }
Example #44
0
            public async Task ConnectionErrorCapturesExceptionsThrownInReceived(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    var       errorsCaught = 0;
                    var       wh           = new TaskCompletionSource <object>();
                    Exception thrown       = new Exception(),
                              caught       = null;

                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/multisend");

                    using (connection)
                    {
                        connection.Received += _ =>
                        {
                            throw thrown;
                        };

                        connection.Error += e =>
                        {
                            caught = e;
                            if (Interlocked.Increment(ref errorsCaught) == 2)
                            {
                                wh.TrySetResult(null);
                            }
                        };

                        await connection.Start(host.Transport);

                        await wh.Task.OrTimeout(TimeSpan.FromSeconds(5));

                        Assert.Equal(thrown, caught);
                    }
                }
            }
Example #45
0
            public void ClientStaysReconnectedAfterDisconnectTimeout(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: null,
                                    connectionTimeout: 2,
                                    disconnectTimeout: 6);

                    var connection     = CreateHubConnection(host);
                    var reconnectingWh = new ManualResetEventSlim();
                    var reconnectedWh  = new ManualResetEventSlim();

                    connection.Reconnecting += () =>
                    {
                        reconnectingWh.Set();
                        Assert.Equal(ConnectionState.Reconnecting, connection.State);
                    };

                    connection.Reconnected += () =>
                    {
                        reconnectedWh.Set();
                        Assert.Equal(ConnectionState.Connected, connection.State);
                    };

                    connection.Start(host.Transport).Wait();

                    // Force reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    Assert.True(reconnectingWh.Wait(TimeSpan.FromSeconds(30)));
                    Assert.True(reconnectedWh.Wait(TimeSpan.FromSeconds(30)));
                    Thread.Sleep(TimeSpan.FromSeconds(15));
                    Assert.NotEqual(ConnectionState.Disconnected, connection.State);

                    connection.Stop();
                }
            }
Example #46
0
        public void Security_PersistentCookie(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, PersistentCookieConfiguration);
                string homePath       = applicationUrl + "Auth/Home";
                string logoutPath     = applicationUrl + string.Format("Auth/Logout?ReturnUrl={0}", new Uri(homePath).AbsolutePath);

                var handler    = new HttpClientHandler();
                var httpClient = new HttpClient(handler);

                // Unauthenticated request
                var response = httpClient.GetAsync(applicationUrl).Result;
                CookiesCommon.IsRedirectedToCookiesLogin(response.RequestMessage.RequestUri, applicationUrl, "Unauthenticated requests not automatically redirected to login page");

                // Valid credentials
                var validPersistingCredentials = new FormUrlEncodedContent(new kvp[] { new kvp("username", "test"), new kvp("password", "test"), new kvp("rememberme", "on") });
                response = httpClient.PostAsync(response.RequestMessage.RequestUri, validPersistingCredentials).Result;
                response.EnsureSuccessStatusCode();
                Assert.Equal <string>(applicationUrl, response.RequestMessage.RequestUri.AbsoluteUri);

                //Verify cookie sent
                Assert.True(handler.CookieContainer.Count == 1, "Did not receive one cookie as expected");
                var cookie = handler.CookieContainer.GetCookies(new Uri(applicationUrl))[0];
                Assert.True(cookie != null && cookie.Name == "KATANACOOKIE", "Cookie with name 'KATANACOOKIE' not found");
                Assert.True((cookie.Expires - DateTime.Now).Days > 10, "Did not receive a persistent cookie");

                //Logout the client
                response = httpClient.GetAsync(logoutPath).Result;
                Assert.True(handler.CookieContainer.Count == 0, "Cookie is not cleared on logout");
                Assert.Equal <string>(homePath, response.RequestMessage.RequestUri.AbsoluteUri);

                //Try accessing protected resource again. It should get redirected to login page
                response = httpClient.GetAsync(applicationUrl).Result;
                CookiesCommon.IsRedirectedToCookiesLogin(response.RequestMessage.RequestUri, applicationUrl, "Request not automatically redirected to login page after cookie expiry");
            }
        }
Example #47
0
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.IISExpress, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.Websockets, MessageBusType.Default)]
        public void ReconnectExceedingReconnectWindowDisconnects(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            // Test cannot be async because if we do host.ShutDown() after an await the connection stops.

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var reconnectWh  = new ManualResetEventSlim();
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Reconnecting += () =>
                    {
                        ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromMilliseconds(500);
                        reconnectWh.Set();
                    };

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    connection.Start(host.Transport).Wait();

                    // Without this the connection start and reconnect can race with eachother resulting in a deadlock.
                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    host.Shutdown();

                    Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(15)), "Reconnect never fired");
                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Example #48
0
        public HostHourCountData GetHourCount(HostType hostType)
        {
            if (hostType != HostType.Weibo)
            {
                throw new NotSupportedException("不支持该类型操作");
            }
            var hostData             = HostBasicData.GetHostData();
            HostHourCountData result = new HostHourCountData()
            {
                HostData = hostData
            };

            //获取HourCount
            HourCountData[] data =
            {
                new HourCountData()
                {
                    Descrption  = Program.JobCounterDesc,
                    HourCounter = Program.JobCounter
                },
            };
            result.HourCounts = data;
            return(result);
        }
Example #49
0
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        public async Task ReconnectionSuccesfulTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new TaskCompletionSource <object>();
                host.Initialize(keepAlive: null, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                using (connection)
                {
                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2));

                    connection.Reconnected += () =>
                    {
                        mre.TrySetResult(null);
                    };

                    await connection.Start(host.Transport);

                    await mre.Task.OrTimeout(TimeSpan.FromSeconds(10));
                }
            }
        }
Example #50
0
            //[InlineData(HostType.IISExpress, TransportType.Websockets)]
            public async Task GroupsReceiveMessages(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/groups");
                    var tcs        = new TaskCompletionSource <string>();
                    connection.Received += data =>
                    {
                        // Should only be called once.
                        tcs.TrySetResult(data);
                    };

                    await connection.Start(host.Transport);

                    // Join the group
                    await connection.Send(new { type = 1, group = "test" }).OrTimeout();

                    // Sent a message
                    await connection.Send(new { type = 3, group = "test", message = "hello to group test" }).OrTimeout();

                    // Leave the group
                    await connection.Send(new { type = 2, group = "test" }).OrTimeout();

                    for (var i = 0; i < 10; i++)
                    {
                        // Send a message
                        await connection.Send(new { type = 3, group = "test", message = "goodbye to group test" }).OrTimeout();
                    }

                    connection.Stop();

                    Assert.Equal("hello to group test", await tcs.Task.OrTimeout());
                }
            }
Example #51
0
            public void ConnectionErrorCapturesExceptionsThrownInReceived(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    var       errorsCaught = 0;
                    var       wh           = new ManualResetEventSlim();
                    Exception thrown       = new Exception(),
                              caught       = null;

                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/multisend");

                    using (connection)
                    {
                        connection.Received += _ =>
                        {
                            throw thrown;
                        };

                        connection.Error += e =>
                        {
                            caught = e;
                            if (Interlocked.Increment(ref errorsCaught) == 2)
                            {
                                wh.Set();
                            }
                        };

                        connection.Start(host.Transport).Wait();

                        Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
                        Assert.Equal(thrown, caught);
                    }
                }
            }
Example #52
0
        public void Static_ValidIfModifiedSince(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, ValidModifiedSinceConfiguration);
                var httpClient     = new HttpClient()
                {
                    BaseAddress = new Uri(applicationUrl)
                };
                var fileContent = File.ReadAllBytes(@"RequirementFiles/Dir1/RangeRequest.txt");

                var response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal <HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);

                //Modified since = lastmodified. Expect a 304
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified;
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal <HttpStatusCode>(HttpStatusCode.NotModified, response.StatusCode);

                //Modified since > lastmodified. Expect a 304
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified.Value.AddMinutes(12);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal <HttpStatusCode>(HttpStatusCode.NotModified, response.StatusCode);

                //Modified since < lastmodified. Expect an OK.
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified.Value.Subtract(new TimeSpan(10 * 1000));
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal <HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //Modified since is an invalid date string. Expect an OK.
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("If-Modified-Since", "InvalidDate");
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal <HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
            }
        }
Example #53
0
        public async Task NoDeadlockWhenBlockingAfterInvokingProxyMethod(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize();
                HubConnection        hubConnection = CreateHubConnection(host);
                ManualResetEventSlim mre           = new ManualResetEventSlim();

                using (hubConnection)
                {
                    var proxy = hubConnection.CreateHubProxy("EchoHub");

                    var called = false;
                    proxy.On <string>("echo", message =>
                    {
                        if (!called)
                        {
                            called = true;
                            proxy.Invoke("EchoCallback", "message");
                        }
                        else
                        {
                            mre.Set();
                        }
                    });

                    await hubConnection.Start(host.Transport);

                    await proxy.Invoke("EchoCallback", "message");

                    Assert.True(mre.Wait(5000));

                    hubConnection.Stop();
                }
            }
        }
Example #54
0
        public async Task ConnectionErrorCapturesExceptionsThrownInClientHubMethod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                var       wh     = new AsyncManualResetEvent();
                Exception thrown = new Exception(),
                          caught = null;

                host.Initialize(messageBusType: messageBusType);

                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var proxy = connection.CreateHubProxy("ChatHub");

                    proxy.On <string>("addMessage", (message) =>
                    {
                        throw thrown;
                    });

                    connection.Error += e =>
                    {
                        caught = e;
                        wh.Set();
                    };

                    await connection.Start(host.Transport);

                    var ignore = proxy.Invoke("Send", "").Catch();

                    Assert.True(await wh.WaitAsync(TimeSpan.FromSeconds(5)));
                    Assert.Equal(thrown, caught);
                }
            }
        }
Example #55
0
 public void update()
 {
     if (socket.Connected)
     {
         ipAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString();
         port      = ((IPEndPoint)socket.RemoteEndPoint).Port;
         type      = HostType.RemoteHost;
     }
     else
     {
         if (socket.IsBound)
         {
             ipAddress = ((IPEndPoint)socket.LocalEndPoint).Address.ToString();
             port      = ((IPEndPoint)socket.LocalEndPoint).Port;
             type      = HostType.LocalHost;
         }
         else
         {
             ipAddress = "";
             port      = 0;
             type      = HostType.NA;
         }
     }
 }
Example #56
0
        public async void Script_Referencing_Specific_Type_Executes()
        {
            var manager = new RuntimeManager(new ManualManagerSettings());

            var hostType = new HostType
            {
                Name = "MathStuff",
                Type = typeof(System.Math)
            };

            var subject = new TestObject();

            await manager.ExecuteAsync("test", "subject.Result = MathStuff.Pow(10,2);",
                                       new List <HostObject> {
                new HostObject {
                    Name = "subject", Target = subject
                }
            },
                                       new List <HostType> {
                hostType
            });

            subject.Result.ShouldEqual(100);
        }
Example #57
0
            // [InlineData(HostType.Memory, TransportType.LongPolling)]
            // [InlineData(HostType.IISExpress, TransportType.Auto)]
            public void GroupCanBeAddedAndMessagedOnConnected(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    var wh = new ManualResetEventSlim();
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/add-group");

                    using (connection)
                    {
                        connection.Received += data =>
                        {
                            Assert.Equal("hey", data);
                            wh.Set();
                        };

                        connection.Start(host.Transport).Wait();
                        connection.SendWithTimeout("");

                        Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
                    }
                }
            }
Example #58
0
        public async Task NoDeadlockWhenBlockingAfterInvokingProxyMethod(HostType hostType, TransportType transportType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize();
                var hubConnection = CreateHubConnection(host);
                var mre           = new TaskCompletionSource <object>();

                using (hubConnection)
                {
                    var proxy = hubConnection.CreateHubProxy("EchoHub");

                    var called = false;
                    proxy.On <string>("echo", message =>
                    {
                        if (!called)
                        {
                            called = true;
                            proxy.Invoke("EchoCallback", "message");
                        }
                        else
                        {
                            mre.TrySetResult(null);
                        }
                    });

                    await hubConnection.Start(host.Transport).OrTimeout();

                    await proxy.Invoke("EchoCallback", "message").OrTimeout();

                    await mre.Task.OrTimeout();

                    hubConnection.Stop();
                }
            }
        }
Example #59
0
        public override SocketTasks StartClient()
        {
            SocketTask task = SocketTask.Working;

            if (m_HostType != HostType.None)
            {
                throw new InvalidOperationException("Already started as " + m_HostType);
            }

            m_HostType = HostType.Client;

            m_NetManager.Start();

            NetPeer peer = m_NetManager.Connect(Address, Port, string.Empty);

            if (peer.Id != 0)
            {
                throw new InvalidPacketException("Server peer did not have id 0: " + peer.Id);
            }

            m_Peers[(ulong)peer.Id] = peer;

            return(task.AsTasks());
        }
Example #60
0
	//생성자.
	public NetworkController(string hostAddress, bool isHost)
	{
		DebugWriterSetup();

		isSynchronized = false;
		m_hostType = isHost ? HostType.Server : HostType.Client;

		GameObject nObj = GameObject.Find("Network");
		m_transport = nObj.GetComponent<TransportUDP>();
		// 동일 단말에서 실행할 수 있게 포트 번호를 변경합니다.
		// 다른 단말에서 실행할 경우 포트 번호가 같은 것을 사용합니다.
		//int listeningPort = isHost ? NetConfig.GAME_PORT : NetConfig.GAME_PORT + 1;


		
		m_transport.StartServer(3098);
		
		
		// 동일 단말에서 실행할 수 있게 포트 번호를 변경합니다.
		// 다른 단말에서 실행할 경우 포트 번호가 같은 것을 사용합니다.
		int remotePort = isHost ? NetConfig.GAME_PORT + 1 : NetConfig.GAME_PORT;



		m_transport.Connect(hostAddress, 3098);

		m_transport.RegisterEventHandler(OnEventHandling);

		GameObject iObj = GameObject.Find("InputManager");
		m_inputManager = iObj.GetComponent<InputManager>();

		for (int i = 0; i < mouseInputBuffer.Length; ++i)
		{
			mouseInputBuffer[i] = new List<MouseData>();
		}
	}