本文整理汇总了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);
}
示例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");
}
}
示例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");
}
}
示例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" });
}
示例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");
}
示例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;
}
示例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");
}
}
示例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));
}
示例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]);
}
示例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;
}
}
示例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");
}