我有带有POST方法端点的Http服务器(用D lang编写)。我想从用.Net编写的非Web客户端将一些命令流式传输到该方法,并且阻止这种流式传输对我来说也很不错,以防万一出了问题,还可以听取来自该服务器的响应。这就是问题所在,看来我应该结束流式传输(或发送零个tcp消息)以获取任何响应。
感谢Wireshark,我知道它的行为是这样的:
一种实施方式:
public async Task Start()
{
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
var json = GetData();
StreamWriter writer = null;
var content = new PushStreamContent(async (stream, httpContent, transportContext) =>
{
writer = new StreamWriter(stream);
writer.AutoFlush = true;
await writer.WriteLineAsync("[" + json);
});
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var message = new HttpRequestMessage(HttpMethod.Post, url);
message.Content = content;
Task.Run(async () =>
{
var result = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);
Console.WriteLine(result.StatusCode);
});
while (true)
{
if(Console.ReadKey().KeyChar == 'a')
{
await writer.WriteLineAsync($",{json}");
}
}
}
答案 0 :(得分:1)
您的方案看起来非常适合SignalR。
基本上,SignalR是一个开源库,可简化向应用程序添加实时Web功能的过程。实时Web功能使服务器端代码可以将内容立即推送到客户端。
您可以使用带以下非核心版本的SignalR 2查找示例:
首先,在服务器端创建以下基本结构:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
现在您需要在客户端创建以下结构:
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-3.1.1.min.js" ></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
您可以了解有关SignalR here的更多信息。