JS WebSocket API-连接到C#服务器时,WebSocket打开握手超时

时间:2019-06-20 00:50:09

标签: javascript c# websocket

因此,我正在尝试使用TcpListenerTcpClient类在C#中模拟回显服务器,该服务器运行在http://127.0.0.1:6502

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace WebServer
{
    class Program
    {
        public static TcpListener Server = new TcpListener(IPAddress.Any, 6502);

        public static void Main(string[] args)
        {
            Server.Start();
            Thread ListenerThread = new Thread(Listener);
            ListenerThread.Start();
        }

        public static void Listener()
        {
            while (true)
            {
                TcpClient C = Server.AcceptTcpClient();
                Console.WriteLine(C.Client.RemoteEndPoint + " Connected");
                Thread WorkerThread = new Thread(Worker);
                WorkerThread.IsBackground = true;
                WorkerThread.Start(C);
            }
        }

        public static void Worker(object Client)
        {
            try
            {
                NetworkStream NS = (Client as TcpClient).GetStream();
                StreamReader SR = new StreamReader(NS);
                StreamWriter SW = new StreamWriter(NS);
                while (true)
                {
                    string Line = SR.ReadLine();
                    Console.WriteLine("Recieved " + Line + " From Client " + (Client as TcpClient).Client.RemoteEndPoint);
                    SW.WriteLine(Line);
                    Console.WriteLine("Sent " + Line + " To Client " + (Client as TcpClient).Client.RemoteEndPoint);
                }
            }
            catch { }
        }
    }
}

在客户端,我有一个网页index.html托管在运行于http://127.0.0.1:8080的静态服务器上,这里我使用WebSocket API创建了一个实时连接服务器。

<script>
    window.addEventListener("load", function() {
        let ws = new WebSocket("ws://127.0.0.1:6502");

        ws.onopen = function() {
            alert("Connection Opened");
            ws.send("A Test Message");
        };

        ws.onmessage = function(e) {
            alert("Recieved: " + e.data);
        };

        ws.onclose = function(e) {
            alert("Connection has been closed");
        };

        ws.onerror = function(e) {
            alert("An error has occured");
        };

    });
</script>

问题是我在控制台中收到以下错误消息:

WebSocket connection to 'ws://127.0.0.1:6502/' failed: WebSocket opening handshake timed out

我在这里做什么错了?

0 个答案:

没有答案