C# HttpListener 接受untiy 上传的视频
时间: 2023-12-02 16:07:23 浏览: 260
C# HttpListener HttpServer WinFrom
要使用C# HttpListener接收Unity上传的视频,可以使用以下步骤:
1. 在Unity中编写脚本,将视频文件转换为字节数组并将其发送到指定的URL。
```csharp
using UnityEngine;
using System.IO;
using System.Net;
public class VideoUploader : MonoBehaviour
{
public string url;
public string filePath;
void Start()
{
byte[] videoBytes = File.ReadAllBytes(filePath);
StartCoroutine(UploadVideo(videoBytes));
}
IEnumerator UploadVideo(byte[] videoBytes)
{
UnityWebRequest request = UnityWebRequest.Put(url, videoBytes);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
Debug.Log("Video uploaded successfully!");
}
else
{
Debug.Log("Video upload failed: " + request.error);
}
}
}
```
2. 在C#中编写HttpListener服务器,以侦听从Unity发送的请求。在服务器代码中,使用`HttpListenerContext`对象从请求中获取视频数据并将其保存到本地文件中。
```csharp
using System;
using System.IO;
using System.Net;
public class HttpServer
{
private HttpListener listener;
private string savePath;
public HttpServer(string prefix, string savePath)
{
listener = new HttpListener();
listener.Prefixes.Add(prefix);
this.savePath = savePath;
}
public void Start()
{
listener.Start();
Console.WriteLine("Server started.");
while (true)
{
HttpListenerContext context = listener.GetContext();
ProcessRequest(context);
}
}
private void ProcessRequest(HttpListenerContext context)
{
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
if (request.HttpMethod == "PUT")
{
byte[] videoBytes = new byte[request.ContentLength64];
int bytesRead = request.InputStream.Read(videoBytes, 0, videoBytes.Length);
if (bytesRead > 0)
{
string fileName = Path.GetFileName(request.Url.LocalPath);
string filePath = Path.Combine(savePath, fileName);
File.WriteAllBytes(filePath, videoBytes);
response.StatusCode = 200;
response.StatusDescription = "OK";
response.OutputStream.Close();
Console.WriteLine("Video saved to: " + filePath);
}
}
}
public void Stop()
{
listener.Stop();
listener.Close();
Console.WriteLine("Server stopped.");
}
}
```
3. 在Main函数中实例化HttpServer并启动它。
```csharp
static void Main(string[] args)
{
string prefix = "http://localhost:8080/";
string savePath = "C:\\Videos";
HttpServer server = new HttpServer(prefix, savePath);
server.Start();
Console.ReadKey();
server.Stop();
}
```
上述代码中,`prefix`是HTTP监听器的前缀,`savePath`是要保存视频文件的本地路径。在Unity中将`url`设置为服务器的`prefix`和视频文件名即可上传视频文件。
阅读全文