0

I found TCPListener code from here. In MainWindow class Im starting server.
Then opening websocket from html page

let socket = new WebSocket("ws://192.168.1.149:1112");

Right after this CPU loads to 25% even if nothing sent to server. Further data sending to server going normal. What to do to prevent CPU load? Please help.

class TcpServer
{
    public string ip;
    public int port;
    private Thread bgThread;

    public void StartListen()
    {
        bgThread = new Thread(new ThreadStart(Start))
        {
            IsBackground = true
        };
        bgThread.Start();

    }

    public void Start()
    {
        TcpListener server = new TcpListener(IPAddress.Parse(ip), port);
        server.Start();

        TcpClient client = server.AcceptTcpClient();
        NetworkStream stream = client.GetStream();

        while (true)
        {
            while (!stream.DataAvailable) ;
            while (client.Available < 3) ; // match against "get"

            byte[] bytes = new byte[client.Available];
            stream.Read(bytes, 0, client.Available);
            string strbytes = Encoding.UTF8.GetString(bytes);

            if(strbytes.StartsWith("GET"))
            {
                Console.WriteLine("=====Handshaking from client=====\n{0}", strbytes);

                string swk = Regex.Match(strbytes, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);

                // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
                byte[] response = Encoding.UTF8.GetBytes(
                    "HTTP/1.1 101 Switching Protocols\r\n" +
                    "Connection: Upgrade\r\n" +
                    "Upgrade: websocket\r\n" +
                    "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");

                stream.Write(response, 0, response.Length);
            }
            else
            {
                bool mask = (bytes[1] & 0b10000000) != 0; 

                int msglen = bytes[1] - 128, 
                offset = 2;

                if (msglen == 126)
                {
                    msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
                    offset = 4;
                }
                else if (msglen == 127)
                {
                    Console.WriteLine("TODO: msglen == 127, needs qword to store msglen");
                }

                if (msglen == 0)
                    Console.WriteLine("msglen == 0");
                else if (mask)
                {
                    try
                    {
                        byte[] decoded = new byte[msglen];
                        byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
                        offset += 4;

                        for (int i = 0; i < msglen; ++i)
                            decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]);

                        string text = Encoding.UTF8.GetString(decoded);
                        
                        // other code
                        
                    }
                    catch(Exception exc)
                    {
                        Console.WriteLine(exc.Message + "\n--------\n" + exc.StackTrace);
                    }
                    
                }
                else
                    Console.WriteLine("mask bit not set");

            }
        }
    }
}

private void startServer()
{
    tcpserver = new TcpServer
    {
        ip = ipbox.Text,
        port = 1112
    };
    tcpserver.StartListen();
}



startServer();

P.S: I have not to say anymore but SO says "It looks like your post is mostly code; please add some more details.". So: some words

axmed2004
  • 113
  • 1
  • 4
  • It is at 25% because it's doing work. Why's that a problem? [See this](https://stackoverflow.com/questions/54598146/why-will-while-true-use-100-of-cpu-resources/54598278) – CodingYoshi Jun 21 '20 at 13:18
  • @CodingYoshi the problem is that my HttpListener with same "while" loop doesnt load CPU – axmed2004 Jun 21 '20 at 13:25
  • Your are using Synchronous instead of Asynchronous methods. You while receive loop is constantly running and using CPU load. Using Asynchronous method you sleep when no data is being received so you do not constantly use CPU. – jdweng Jun 21 '20 at 15:45

0 Answers0