当前位置: 首页>>代码示例>>C#>>正文


C# Connection.Send方法代码示例

本文整理汇总了C#中System.Net.Connection.Send方法的典型用法代码示例。如果您正苦于以下问题:C# Connection.Send方法的具体用法?C# Connection.Send怎么用?C# Connection.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Connection的用法示例。


在下文中一共展示了Connection.Send方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: server_ClientConnceted

 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);
 }
开发者ID:nishant-chaturvedi,项目名称:TinyWebSocket,代码行数:7,代码来源:Program.cs

示例2: HandleAnResponseWithDifferentContentType

        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");
            }
        }
开发者ID:JudoPay,项目名称:DotNetSDK,代码行数:29,代码来源:ConnectionTests.cs

示例3: HandleAn400

        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");
            }
        }
开发者ID:JudoPay,项目名称:DotNetSDK,代码行数:29,代码来源:ConnectionTests.cs

示例4: RunRawConnection

        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" });
        }
开发者ID:Coladela,项目名称:signalr-chat,代码行数:13,代码来源:CommonClient.cs

示例5: RunAuth

        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");
        }
开发者ID:Coladela,项目名称:signalr-chat,代码行数:34,代码来源:CommonClient.cs

示例6: ProcessHeadersAndUpgrade

        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;
        }
开发者ID:mpotra,项目名称:NetGain,代码行数:26,代码来源:WebSocketsClientProcessor.cs

示例7: HandleConnectionError

        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");
            }
        }
开发者ID:JudoPay,项目名称:DotNetSDK,代码行数:28,代码来源:ConnectionTests.cs

示例8: ExplicitUserAgentSendsExplicitValue

        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));
        }
开发者ID:JudoPay,项目名称:DotNetSDK,代码行数:38,代码来源:ConnectionTests.cs

示例9: ShouldSendData

        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]);
        }
开发者ID:jpalmero9,项目名称:peer2net,代码行数:24,代码来源:ConnectionTests.cs

示例10: WriteBodyToConnection

		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;
			}
		}
开发者ID:remobjects,项目名称:internetpack,代码行数:50,代码来源:HttpRequestResponse.cs

示例11: RunBasicAuth

        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");            
        }
开发者ID:nirmana,项目名称:SignalR,代码行数:23,代码来源:CommonClient.cs


注:本文中的System.Net.Connection.Send方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。