
Websocket是一种全双工通信协议,能够实现客户端和服务端之间的实时通信。它基于TCP协议,并且允许服务器主动向客户端推送数据,同时也允许客户端向服务器发送数据。
长轮询是一种技术,客户端向服务器发送一个请求,并且服务器保持连接打开直到有数据可以返回给客户端。如果在指定的时间内没有数据可用,则服务器会关闭连接,客户端需要重新建立连接并再次发起请求。
流式响应
当客户端返回流的时候,客户端可以实时捕获到返回的信息,并不需要等全部Response结束了再处理。
返回文本内容
服务端
[HttpPost("text"]
public async Task Post(
{
string filePath = "文档.txt";
Response.ContentType = "application/octet-stream";
var reader = new StreamReader(filePath;
var buffer = new Memory<char>(new char[5];
int writeLength = 0;
//每次读取5个字符写入到流中
while ((writeLength = await reader.ReadBlockAsync(buffer > 0
{
if (writeLength < buffer.Length
{
buffer = buffer[..writeLength];
}
await Response.WriteAsync(buffer.ToString(;
await Task.Delay(100;
}
}
客户端
- C# HttpClient
public async void GetText(
{
var url = "http://localhost:5000/config/text";
var client = new HttpClient(;
using HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url;
var response = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead;
await using var stream = await response.Content.ReadAsStreamAsync(;
var bytes = new byte[20];
int writeLength = 0;
while ((writeLength = stream.Read(bytes, 0, bytes.Length > 0
{
Console.Write(Encoding.UTF8.GetString(bytes, 0, writeLength;
}
Console.WriteLine(;
Console.WriteLine("END";
}
HttpCompletionOption枚举有两个值,默认情况下使用的是ResponseContentRead
-
ResponseHeadersRead:一旦获取到响应头即完成操作,不用等到整个内容响应
ResponseContentRead:等到整个响应完成才完成操作
- js XMLHttpRequest
<script>
var div = document.getElementById("content"
var url = "http://localhost:5000/config/text"
var client = new XMLHttpRequest(
client.open("POST", url
client.onprogress = function (progressEvent {
div.innerText = progressEvent.target.responseText
}
client.onloadend = function (progressEvent {
div.append("END"
}
client.send(
</script>
用axios请求就是监听onDownloadProgress 了。
Response Header中的
Content-Type来解析服务端响应体的。如果后端接口没有设置Response.ContentType = "application/octet-stream",onprogress只会在响应全部完成后触发。
返回图片
服务端
[HttpGet("img"]
public async Task Stream(
{
string filePath = "pixelcity.png";
new FileExtensionContentTypeProvider(.TryGetContentType(filePath, out string contentType;
Response.ContentType = contentType ?? "application/octet-stream";
var fileStream = System.IO.File.OpenRead(filePath;
var bytes = new byte[1024];
int writeLength = 0;
while ((writeLength = fileStream.Read(bytes, 0, bytes.Length > 0
{
await Response.Body.WriteAsync(bytes, 0, writeLength;
await Task.Delay(100;
}
}