我想创建:
到目前为止,这是我的代码:
客户端
public async Task SubscribeToUpdates()
{
this.subscribe = false;
try
{
var client = new HttpClient();
var stream = await client.GetStreamAsync(Constants.SubscribeEndpoint);
using (var rdr = new StreamReader(stream))
{
while (!rdr.EndOfStream && !subscribe)
{
var result = rdr.ReadLine();
var json = JObject.Parse(result);
this.HandleUpdateResult(json); // todo
}
}
}
catch (Exception e)
{
// TO do: log exception
}
}
服务器,无法正常工作
[HttpGet]
public Task PushStreamContent()
{
HttpContext.Response.ContentType = "text/event-stream";
var sourceStream = randomStream();
return sourceStream.CopyToAsync(HttpContext.Response.Body);
}
public static Stream randomStream()
{
Random rnd = new Random();
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(JsonConvert.SerializeObject(rnd.News(0,255));
writer.Flush();
stream.Position = 0;
return stream;
}
问题:
正在使用.Net版本
我已经设法为.net标准编写代码,但不是.net核心。原因是.net core:/。
中不存在PushStreamContent [HttpGet]
public HttpResponseMessage PushStreamContent()
{
var response = Request.CreateResponse(HttpStatusCode.Accepted);
response.Content =
new PushStreamContent((stream, content, context) =>
{
var plotter = new Plotter();
while (true)
{
using (var writer = new StreamWriter(stream))
{
Random rnd = new Random()
writer.WriteLine(rnd.Next(0,255));
stream.Flush();
Thread.Sleep(20);
}
}
});
return response;
}
答案 0 :(得分:2)
感谢前面的“Mike McCaughan”和“Joel Harkes”的回答,我重新考虑了通信过程并从REST切换到Websockets。
您可以在.net Core(和Xamarin.Forms)here中找到一个很好的示例如何使用WebSockets。您将不得不使用Nuget包“Websockets.PCL”。