C# HttpListener 接受untiy 上传的视频,俩端显示进度
时间: 2023-12-10 16:40:24 浏览: 170
要实现C# HttpListener接收Unity上传的视频,并且在两端显示进度,你可以按照以下步骤进行操作:
1. 在Unity中使用UnityWebRequest类来上传视频,同时在上传时通过POST方式发送进度信息。
```csharp
IEnumerator UploadVideo()
{
UnityWebRequest request = UnityWebRequest.Post(uploadURL, form);
request.SendWebRequest();
while (!request.isDone)
{
float progress = request.uploadProgress;
// 通过POST方式发送进度信息
UnityWebRequest progressRequest = UnityWebRequest.Post(progressURL, progressForm);
progressRequest.SendWebRequest();
yield return null;
}
}
```
2. 在C#中使用HttpListener接收视频和进度信息。
```csharp
public async Task StartListener()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
if (request.HttpMethod == "POST" && request.Url.LocalPath == "/video")
{
// 接收视频
using (var stream = File.Create("video.mp4"))
{
await request.InputStream.CopyToAsync(stream);
}
}
else if (request.HttpMethod == "POST" && request.Url.LocalPath == "/progress")
{
// 接收进度信息
string progress = new StreamReader(request.InputStream).ReadToEnd();
Console.WriteLine("Progress: " + progress);
}
}
}
```
3. 在接收进度信息的同时,可以使用WebSocket来将进度信息发送到另一个客户端。
```csharp
public async Task StartWebSocket()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8081/");
listener.Start();
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null);
WebSocket webSocket = webSocketContext.WebSocket;
while (webSocket.State == WebSocketState.Open)
{
HttpListenerRequest request = await webSocketContext.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
HttpListenerResponse response = context.Response;
// 发送进度信息
string progress = GetProgress();
byte[] bytes = Encoding.UTF8.GetBytes(progress);
await webSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
```
4. 在另一个客户端中使用WebSocket来接收进度信息,并且在界面上显示出来。
```csharp
public async Task StartWebSocket()
{
using (ClientWebSocket webSocket = new ClientWebSocket())
{
Uri serverUri = new Uri("ws://localhost:8081/");
await webSocket.ConnectAsync(serverUri, CancellationToken.None);
while (webSocket.State == WebSocketState.Open)
{
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
string progress = Encoding.UTF8.GetString(buffer, 0, result.Count);
// 在界面上显示进度信息
Console.WriteLine("Progress: " + progress);
}
}
}
}
```
通过以上步骤,你就可以实现C# HttpListener接收Unity上传的视频,并且在两端显示进度了。
阅读全文