コード例 #1
0
 static async void server_ClientConnceted(object sender, Connection con)
 {
     con.DataReceived += con_DataReceived;
     StringBuilder sb = new StringBuilder();
     var sampleData = File.ReadAllText(@"C:\PersonalProjects\TinyWebSocket\TinyWebSocket.Host\sample.txt", Encoding.UTF8);
     await con.Send(sampleData);
 }
コード例 #2
0
ファイル: ConnectionTests.cs プロジェクト: JudoPay/DotNetSDK
        public void HandleAnResponseWithDifferentContentType()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("errorMessage") };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/text");
            var httpClient = Substitute.For<IHttpClient>();
            httpClient.SendAsync(Arg.Any<HttpRequestMessage>()).Returns(Task.FromResult(response));
            var connection = new Connection(httpClient, DotNetLoggerFactory.Create, "http://test.com");
            var generatedException = false;

            try
            {
                connection.Send<string>(HttpMethod.Get, "/thisIsATest").Wait();
            }
            catch (AggregateException e)
            {
                var aggregatedException = e.Flatten();
                Assert.AreEqual(1, aggregatedException.InnerExceptions.Count);
                var badResponseError = aggregatedException.InnerExceptions.FirstOrDefault();
                Assert.IsInstanceOf<BadResponseError>(badResponseError);
                Assert.IsNotNull(badResponseError);
                Assert.AreEqual("Response format isn't valid it should have been application/json but was application/text", badResponseError.Message);
                generatedException = true;
            }

            if (!generatedException)
            {
                Assert.Fail("Send should have thrown an HttpError exception");
            }
        }
コード例 #3
0
ファイル: ConnectionTests.cs プロジェクト: JudoPay/DotNetSDK
        public void HandleAn400()
        {
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("errorMessage") };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var httpClient = Substitute.For<IHttpClient>();
            httpClient.SendAsync(Arg.Any<HttpRequestMessage>()).Returns(Task.FromResult(response));
            var connection = new Connection(httpClient, DotNetLoggerFactory.Create, "http://test.com");
            var generatedException = false;

            try
            {
                connection.Send<string>(HttpMethod.Get, "/thisIsATest").Wait();
            }
            catch (AggregateException e)
            {
                var aggregatedException = e.Flatten();
                Assert.AreEqual(1, aggregatedException.InnerExceptions.Count);
                var httpError = aggregatedException.InnerExceptions.FirstOrDefault();
                Assert.IsInstanceOf<HttpError>(httpError);
                // ReSharper disable once PossibleNullReferenceException
                Assert.AreEqual("Status Code : BadRequest, with content: errorMessage", httpError.Message);
                generatedException = true;
            }

            if (!generatedException)
            {
                Assert.Fail("Send should have thrown an HttpError exception");
            }
        }
コード例 #4
0
ファイル: CommonClient.cs プロジェクト: Coladela/signalr-chat
        private async Task RunRawConnection(string serverUrl)
        {
            string url = serverUrl + "raw-connection";

            var connection = new Connection(url);
            connection.TraceWriter = _traceWriter;

            await connection.Start();
            connection.TraceWriter.WriteLine("transport.Name={0}", connection.Transport.Name);

            await connection.Send(new { type = 1, value = "first message" });
            await connection.Send(new { type = 1, value = "second message" });
        }
コード例 #5
0
ファイル: CommonClient.cs プロジェクト: Coladela/signalr-chat
        private async Task RunAuth(string serverUrl)
        {
            string url = serverUrl + "cookieauth";

            var handler = new HttpClientHandler();
            handler.CookieContainer = new CookieContainer();
            using (var httpClient = new HttpClient(handler))
            {
                var content = string.Format("UserName={0}&Password={1}", "user", "password");
                var response = httpClient.PostAsync(url + "/Account/Login", new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
            }

            var connection = new Connection(url + "/echo");
            connection.TraceWriter = _traceWriter;
            connection.Received += (data) => connection.TraceWriter.WriteLine(data);
#if !ANDROID && !iOS
            connection.CookieContainer = handler.CookieContainer;
#endif
            await connection.Start();
            await connection.Send("sending to AuthenticatedEchoConnection");

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;
#if !ANDROID && !iOS
            hubConnection.CookieContainer = handler.CookieContainer;
#endif
            var hubProxy = hubConnection.CreateHubProxy("AuthHub");
            hubProxy.On<string, string>("invoked", (connectionId, date) => hubConnection.TraceWriter.WriteLine("connectionId={0}, date={1}", connectionId, date));

            await hubConnection.Start();
            hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name);

            await hubProxy.Invoke("InvokedFromClient");
        }
コード例 #6
0
        protected override int ProcessHeadersAndUpgrade(NetContext context, Connection connection, Stream input, Stream additionalData, int additionalOffset)
        {
            string requestLine;
            var headers = ParseHeaders(input, out requestLine);
            if (!string.Equals(headers["Upgrade"], "WebSocket", StringComparison.InvariantCultureIgnoreCase)
                || !string.Equals(headers["Connection"], "Upgrade", StringComparison.InvariantCultureIgnoreCase)
                || headers["Sec-WebSocket-Accept"] != expected)
            {
                throw new InvalidOperationException();
            }

            lock (this)
            {
                AddMatchingExtensions(headers, connection, context.Extensions);
                var protocol = new WebSocketsProcessor_RFC6455_13(true);
                connection.SetProtocol(protocol);
                if (pending != null)
                {
                    while (pending.Count != 0)
                    {
                        connection.Send(context, pending.Dequeue());
                    }
                }
            }
            return 0;
        }
コード例 #7
0
 protected override int ProcessHeadersAndUpgrade(NetContext context, Connection connection, Stream input, Stream additionalData, int additionalOffset)
 {
     string requestLine;
     var headers = ParseHeaders(input, out requestLine);
     if (!string.Equals(headers["Upgrade"], "WebSocket", StringComparison.InvariantCultureIgnoreCase)
         || !string.Equals(headers["Connection"], "Upgrade", StringComparison.InvariantCultureIgnoreCase))
     {
         throw new InvalidOperationException();
     }
     
     lock (this)
     {
         var protocol = new WebSocketsProcessor_Hixie76_00.Client(expectedSecurityResponse);
         expectedSecurityResponse = null; // use once only
         connection.SetProtocol(protocol);
         if (pending != null)
         {
             while (pending.Count != 0)
             {
                 connection.Send(context, pending.Dequeue());
             }
         }
     }
     return 0;
 }
コード例 #8
0
ファイル: ConnectionTests.cs プロジェクト: JudoPay/DotNetSDK
        public void HandleConnectionError()
        {
            var httpClient = Substitute.For<IHttpClient>();
            httpClient.When(x => x.SendAsync(Arg.Any<HttpRequestMessage>()))
                .Do(callInfo => { throw new HttpRequestException("A problem reaching destination", new Exception("Unreachable host")); });
            var connection = new Connection(httpClient, DotNetLoggerFactory.Create, "http://test.com");
            var generatedException = false;

            try
            {
                connection.Send<string>(HttpMethod.Get, "/thisIsATest").Wait();
            }
            catch (AggregateException e)
            {
                var aggregatedException = e.Flatten();
                Assert.AreEqual(1, aggregatedException.InnerExceptions.Count);
                var connectionError = aggregatedException.InnerExceptions.FirstOrDefault();
                Assert.IsInstanceOf<ConnectionError>(connectionError);
                Assert.IsNotNull(connectionError);
                Assert.AreEqual("Unreachable host", connectionError.Message);
                generatedException = true;
            }

            if (!generatedException)
            {
                Assert.Fail("Send should have thrown an HttpError exception");
            }
        }
コード例 #9
0
ファイル: ConnectionTests.cs プロジェクト: JudoPay/DotNetSDK
        public async Task ExplicitUserAgentSendsExplicitValue()
        {
            var httpClient = Substitute.For<IHttpClient>();
            var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent((@"{
                            results : [{
                                receiptId : '134567',
                                type : 'Create',
                                judoId : '12456',
                                originalAmount : 20,
                                amount : 20,
                                netAmount : 20,
                                cardDetails :
                                    {
                                        cardLastfour : '1345',
                                        endDate : '1214',
                                        cardToken : 'ASb345AE',
                                        cardType : 'VISA'
                                    },
                                currency : 'GBP',
                                consumer : 
                                    {
                                        consumerToken : 'B245SEB',
                                        yourConsumerReference : 'Consumer1'
                                    }
                             }]}")) };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var responseTask = new TaskCompletionSource<HttpResponseMessage>();
            responseTask.SetResult(response);
            httpClient.SendAsync(Arg.Any<HttpRequestMessage>()).Returns(responseTask.Task);

            var connection = new Connection(httpClient, DotNetLoggerFactory.Create, "http://test.com");
            var paymentModel = new CardPaymentModel { UserAgent = "SomeText" };

            await connection.Send(HttpMethod.Post, "http://foo", null, null, paymentModel);

            await httpClient.Received().SendAsync(Arg.Is<HttpRequestMessage>(r => r.Headers.UserAgent.First().Product.Name == paymentModel.UserAgent));
        }
コード例 #10
0
ファイル: ConnectionTests.cs プロジェクト: jpalmero9/peer2net
        public void ShouldSendData()
        {
            var localConnectionWaiter = new ManualResetEvent(false);
            var remoteConnectionWaiter = new ManualResetEvent(false);

            Connection remoteConnection = null;
            _remote.ConnectionRequested += (sender, args) => {
                remoteConnection = new Connection(args.Socket);
                remoteConnectionWaiter.Set();
            };

            var localConnection = new Connection(new IPEndPoint(IPAddress.Loopback, 9999));
            localConnection.Connect(c => localConnectionWaiter.Set());
            WaitHandle.WaitAll(new WaitHandle[] { localConnectionWaiter, remoteConnectionWaiter });
            localConnectionWaiter.Reset();
            remoteConnectionWaiter.Reset();

            var remoteBuffer = new Buffer(new byte[1]);
            remoteConnection.Receive(remoteBuffer, (i, b) => remoteConnectionWaiter.Set());
            localConnection.Send(new Buffer(new byte[] { 0xf1 }), (i, b) => localConnectionWaiter.Set());
            WaitHandle.WaitAll(new WaitHandle[] { localConnectionWaiter, remoteConnectionWaiter });

            Assert.AreEqual(0xf1, remoteBuffer.Segment.Array[0]);
        }
コード例 #11
0
		public virtual void WriteBodyToConnection(Connection connection)
		{
			try
			{
				if (HasOnTransferProgress)
				{
					connection.OnBytesSent += HandleOnBytesSent;
					connection.ResetStatistics();
				}

				switch (ContentSource)
				{
					case ContentSource.ContentBytes:
						TriggerOnTransferStart(TransferDirection.Send, ContentBytes.Length);
						connection.Send(ContentBytes);
						TriggerOnTransferEnd(TransferDirection.Send);
						break;

					case ContentSource.ContentStream:
						TriggerOnTransferStart(TransferDirection.Send, ContentStream.Length);
						Byte[] lBuffer = new Byte[BUFFER_SIZE];
						Int32 lBytesRead;
						do
						{
							lBytesRead = ContentStream.Read(lBuffer, 0, BUFFER_SIZE);
							if (lBytesRead != 0) connection.Send(lBuffer, 0, lBytesRead);
						}
						while (lBytesRead > 0);

						if (CloseStream)
							ContentStream.Close();

						TriggerOnTransferEnd(TransferDirection.Send);
						break;

					case ContentSource.ContentNone:
						// No action needed
						break;
				}

				if (HasOnTransferProgress)
					connection.OnBytesSent -= HandleOnBytesSent;
			}
			finally
			{
				fContentBytes = null;
				fContentStream = null;
				fContentString = null;
			}
		}
コード例 #12
0
ファイル: CommonClient.cs プロジェクト: nirmana/SignalR
        private async Task RunBasicAuth(string serverUrl)
        {
            string url = serverUrl + "basicauth";

            var connection = new Connection(url + "/echo");
            connection.TraceWriter = _traceWriter;
            connection.Received += (data) => connection.TraceWriter.WriteLine(data);
            connection.Credentials = new NetworkCredential("user", "password");
            await connection.Start();
            await connection.Send("sending to AuthenticatedEchoConnection");

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;
            hubConnection.Credentials = new NetworkCredential("user", "password");

            var hubProxy = hubConnection.CreateHubProxy("AuthHub");
            hubProxy.On<string, string>("invoked", (connectionId, date) => hubConnection.TraceWriter.WriteLine("connectionId={0}, date={1}", connectionId, date));

            await hubConnection.Start();            
            hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name);

            await hubProxy.Invoke("InvokedFromClient");            
        }