c# - 套接字转换为中止状态
问题描述
我正在尝试编写“代理”来拦截本地环境中一个端口上的通信。目前我正在努力让它甚至接受套接字连接。
class Program
{
public static WebSocketContext WSContext = null;
static void Main(string[] args)
{
FakeDevice();
}
protected async static void FakeDevice()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:4033/");
listener.Start();
var context = listener.GetContext();
while (listener.IsListening)
{
Process(context);
}
}
protected async static void Process(HttpListenerContext context)
{
if (context.Request.IsWebSocketRequest)
{
if(WSContext == null)
{
WSContext = await context.AcceptWebSocketAsync(subProtocol: null);
return;
}
WebSocket socket = WSContext.WebSocket;
try
{
byte[] receiveBuffer = new byte[1024];
while (socket.State == WebSocketState.Open)
{
WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
else
{
await socket.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, receiveResult.Count), WebSocketMessageType.Text, receiveResult.EndOfMessage, CancellationToken.None);
}
}
}
catch (Exception e)
{
Console.WriteLine($"Exception message: {e.Message.ToString()}");
}
finally
{
if (socket != null)
{
socket.Dispose();
}
}
}
else
{
Console.WriteLine("NotWs");
}
}
}
即使当我new WebSocket("ws://localhost:4033")
从浏览器控制台调用时,我也会收到异常并且连接正在更改为中止。
我究竟做错了什么?
解决方案
推荐阅读
- c# - xUnit、SpecFlow Selenium 和 ITestOutputHelper 问题
- r - 如何对具有相同 ID 的所有观察结果进行变异?
- ansible - 从角色复制整个文件夹结构与现有文件合并/覆盖
- python - 当函数调用很长时,VS Code for Python 进入新行
- python - 在 stepik 上上传时超过 python 的时间限制
- javascript - 在 forEach 中使用替换字符串方法
- google-sheets - 在 Google 表格中的等号后使用通配符 - SUM IMPORTRANGE
- python - 卸载后在 Windows 开始菜单中显示 Python
- bash - bash将具有特定前缀的所有环境变量导出到文件夹
- javascript - JS:当你不关心返回值时,如何解决一个承诺?