Fixing SocialWeather sample

This commit is contained in:
Pawel Kadluczka 2017-05-02 21:18:55 -07:00 committed by Pawel Kadluczka
parent 1da4e07fff
commit d73b490b69
3 changed files with 20 additions and 14 deletions

View File

@ -4,9 +4,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Sockets;
namespace SocialWeather
@ -38,7 +37,14 @@ namespace SocialWeather
var formatter = _formatterResolver.GetFormatter<T>(connection.Metadata.Get<string>("formatType"));
var ms = new MemoryStream();
await formatter.WriteAsync(data, ms);
await connection.Transport.Output.WriteAsync(new Message(ms.ToArray(), MessageType.Binary, endOfMessage: true));
var context = (HttpContext)connection.Metadata[typeof(HttpContext)];
var format =
string.Equals(context.Request.Query["format"], "binary", StringComparison.OrdinalIgnoreCase)
? MessageType.Binary
: MessageType.Text;
connection.Transport.Output.TryWrite(new Message(ms.ToArray(), format, endOfMessage: true));
}
}

View File

@ -35,13 +35,16 @@ namespace SocialWeather
var formatter = _formatterResolver.GetFormatter<WeatherReport>(
connection.Metadata.Get<string>("formatType"));
while (true)
while (await connection.Transport.Input.WaitToReadAsync())
{
Message message = await connection.Transport.Input.ReadAsync();
var stream = new MemoryStream();
await stream.WriteAsync(message.Payload, 0, message.Payload.Length);
WeatherReport weatherReport = await formatter.ReadAsync(stream);
await _lifetimeManager.SendToAllAsync(weatherReport);
if (connection.Transport.Input.TryRead(out var message))
{
var stream = new MemoryStream();
await stream.WriteAsync(message.Payload, 0, message.Payload.Length);
stream.Position = 0;
var weatherReport = await formatter.ReadAsync(stream);
await _lifetimeManager.SendToAllAsync(weatherReport);
}
}
}
}

View File

@ -231,17 +231,14 @@ namespace Microsoft.AspNetCore.Sockets
private ConnectionState CreateConnection(HttpContext context)
{
var format =
string.Equals(context.Request.Query["format"], "binary", StringComparison.OrdinalIgnoreCase)
? MessageType.Binary
: MessageType.Text;
var state = _manager.CreateConnection();
state.Connection.User = context.User;
// TODO: this is wrong. + how does the user add their own metadata based on HttpContext
var formatType = (string)context.Request.Query["formatType"];
state.Connection.Metadata["formatType"] = string.IsNullOrEmpty(formatType) ? "json" : formatType;
state.Connection.Metadata[typeof(HttpContext)] = context;
return state;
}