首页 > 解决方案 > 套接字转换为中止状态

问题描述

我正在尝试编写“代理”来拦截本地环境中一个端口上的通信。目前我正在努力让它甚至接受套接字连接。

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#websockethttplistener

解决方案


推荐阅读