在C#中,可以通過WebSocket來發送文件。下面是一個簡單的示例代碼,演示如何通過WebSocket發送文件:
using System;
using System.IO;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening for incoming connections...");
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
using (WebSocket webSocket = webSocketContext.WebSocket)
{
string filePath = "path/to/your/file.txt";
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, bytesRead), WebSocketMessageType.Binary, true, CancellationToken.None);
}
}
}
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
}
在上面的代碼中,我們創建了一個簡單的HttpListener來監聽指定的端口,并處理WebSocket請求。當有WebSocket連接時,我們打開要發送的文件,并將其內容通過WebSocket發送給客戶端。請確保替換filePath
變量的值為您要發送的文件的實際路徑。
請注意,上面的示例僅演示了如何從文件中讀取數據并通過WebSocket發送。在實際應用中,您可能需要添加更多的錯誤處理和邏輯來處理各種情況。