在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(buffer, 0, bytesRead), WebSocketMessageType.Binary, true, CancellationToken.None);
}
}
}
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
}
在上面的代码中,我们创建了一个简单的HttpListener来监听指定的端口,并处理WebSocket请求。当有WebSocket连接时,我们打开要发送的文件,并将其内容通过WebSocket发送给客户端。请确保替换filePath
变量的值为您要发送的文件的实际路径。
请注意,上面的示例仅演示了如何从文件中读取数据并通过WebSocket发送。在实际应用中,您可能需要添加更多的错误处理和逻辑来处理各种情况。