【问题标题】:woes in trying to set up a web socket connection in .NET尝试在 .NET 中建立 Web 套接字连接时遇到麻烦
【发布时间】:2011-09-20 03:43:00
【问题描述】:

我有我的 index.aspx 文件:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="index.aspx.vb" Inherits="Web_Socket.index" %>

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script>
        var stockTickerWebSocket = new WebSocket("ws://localhost:14970/ws");
        stockTickerWebSocket.onopen = function (evt) {
            alert("Stock Ticker Connection open …");
        };
        stockTickerWebSocket.onmessage = function (evt) {
            alert("Received Ticker Update: " + evt.data);
        };
        stockTickerWebSocket.onclose = function (evt) {
            alert("Connection closed.");
        };
        stockTickerWebSocket.postMessage("TEST MESSAGE");


</script>
</body>
</html>

所以基本上我想我需要创建一个指向 ws://localhost:14970/ws 的文件?会是什么文件? (可能是一个愚蠢的问题,但因为它没有扩展名..)

我从某个地方得到了这段代码,WebSocketServer.cs:

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace WebSocketServer
{
    public enum ServerLogLevel { Nothing, Subtle, Verbose };
    public delegate void ClientConnectedEventHandler(WebSocketConnection sender, EventArgs e);

    public class WebSocketServer
    {
        #region private members
        private string webSocketOrigin;     // location for the protocol handshake
        private string webSocketLocation;   // location for the protocol handshake
        #endregion

        public event ClientConnectedEventHandler ClientConnected;

        /// <summary>
        /// TextWriter used for logging
        /// </summary>
        public TextWriter Logger { get; set; }     // stream used for logging

        /// <summary>
        /// How much information do you want, the server to post to the stream
        /// </summary>
        public ServerLogLevel LogLevel = ServerLogLevel.Subtle;

        /// <summary>
        /// Gets the connections of the server
        /// </summary>
        public List<WebSocketConnection> Connections { get; private set; }

        /// <summary>
        /// Gets the listener socket. This socket is used to listen for new client connections
        /// </summary>
        public Socket ListenerSocker { get; private set; }

        /// <summary>
        /// Get the port of the server
        /// </summary>
        public int Port { get; private set; }


        public WebSocketServer(int port, string origin, string location)
        {
            Port = port;
            Connections = new List<WebSocketConnection>();
            webSocketOrigin = origin;
            webSocketLocation = location;
        }

        /// <summary>
        /// Starts the server - making it listen for connections
        /// </summary>
        public void Start()
        {
            // create the main server socket, bind it to the local ip address and start listening for clients
            ListenerSocker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Loopback, Port);
            ListenerSocker.Bind(ipLocal);
            ListenerSocker.Listen(100);
            LogLine(DateTime.Now + "> server stated on " + ListenerSocker.LocalEndPoint, ServerLogLevel.Subtle);
            ListenForClients();
        }

        // look for connecting clients
        private void ListenForClients()
        {
            ListenerSocker.BeginAccept(new AsyncCallback(OnClientConnect), null);
        }

        private void OnClientConnect(IAsyncResult asyn)
        {
            // create a new socket for the connection
            var clientSocket = ListenerSocker.EndAccept(asyn);

            // shake hands to give the new client a warm welcome
            ShakeHands(clientSocket);

            // oh joy we have a connection - lets tell everybody about it
            LogLine(DateTime.Now + "> new connection from " + clientSocket.LocalEndPoint, ServerLogLevel.Subtle);



            // keep track of the new guy
            var clientConnection = new WebSocketConnection(clientSocket);
            Connections.Add(clientConnection);
            clientConnection.Disconnected += new WebSocketDisconnectedEventHandler(ClientDisconnected);

            // invoke the connection event
            if (ClientConnected != null)
                ClientConnected(clientConnection, EventArgs.Empty);

            if (LogLevel != ServerLogLevel.Nothing)
                clientConnection.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);



            // listen for more clients
            ListenForClients();
        }

        void ClientDisconnected(WebSocketConnection sender, EventArgs e)
        {
            Connections.Remove(sender);
            LogLine(DateTime.Now + "> " + sender.ConnectionSocket.LocalEndPoint + " disconnected", ServerLogLevel.Subtle);
        }

        void DataReceivedFromClient(WebSocketConnection sender, DataReceivedEventArgs e)
        {
            Log(DateTime.Now + "> data from " + sender.ConnectionSocket.LocalEndPoint, ServerLogLevel.Subtle);
            Log(": " + e.Data + "\n" + e.Size + " bytes", ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Subtle);
        }


        /// <summary>
        /// send a string to all the clients (you spammer!)
        /// </summary>
        /// <param name="data">the string to send</param>
        public void SendToAll(string data)
        {
            Connections.ForEach(a => a.Send(data));
        }

        /// <summary>
        /// send a string to all the clients except one
        /// </summary>
        /// <param name="data">the string to send</param>
        /// <param name="indifferent">the client that doesn't care</param>
        public void SendToAllExceptOne(string data, WebSocketConnection indifferent)
        {
            foreach (var client in Connections)
            {
                if (client != indifferent)
                    client.Send(data);
            }
        }

        /// <summary>
        /// Takes care of the initial handshaking between the the client and the server
        /// </summary>
        private void ShakeHands(Socket conn)
        {
            using (var stream = new NetworkStream(conn))
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            {
                //read handshake from client (no need to actually read it, we know its there):
                LogLine("Reading client handshake:", ServerLogLevel.Verbose);
                string r = null;
                while (r != "")
                {
                    r = reader.ReadLine();
                    LogLine(r, ServerLogLevel.Verbose);
                }

                // send handshake to the client
                writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
                writer.WriteLine("Upgrade: WebSocket");
                writer.WriteLine("Connection: Upgrade");
                writer.WriteLine("WebSocket-Origin: " + webSocketOrigin);
                writer.WriteLine("WebSocket-Location: " + webSocketLocation);
                writer.WriteLine("");
            }


            // tell the nerds whats going on
            LogLine("Sending handshake:", ServerLogLevel.Verbose);
            LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
            LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
            LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
            LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
            LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Verbose);

            LogLine("Started listening to client", ServerLogLevel.Verbose);
            //conn.Listen();
        }

        private void Log(string str, ServerLogLevel level)
        {
            if (Logger != null && (int)LogLevel >= (int)level)
            {
                Logger.Write(str);
            }
        }

        private void LogLine(string str, ServerLogLevel level)
        {
            Log(str + "\r\n", level);
        }
    }
}

所以现在我的问题是我如何WebSocketServer.cs 连接到index.aspx

首先,我想要完成的只是让 Web Sockets 工作,并建立连接,然后alert("Stock Ticker Connection open …");

【问题讨论】:

  • 您将运行将侦听配置端口的服务器。然后运行 ​​ASP.NET 应用程序,导航到该页面,它将打开套接字连接。我看不出它还能如何工作?
  • 您是什么意思运行将侦听配置端口的服务器? ASP.NET 应用程序不是服务器本身吗(就像我们做 AJAX 时,我们不需要运行任何服务器)?

标签: c# javascript asp.net vb.net


【解决方案1】:

WebSocketServer.cs 应该在单独的应用程序中运行,例如控制台应用程序或 Windows 服务。你打电话给Start(),它会监听来自客户端的连接。不涉及 ASP.NET。您可以使用常规的 HTML 页面:它是充当客户端的 Javascript 代码。

您还需要考虑客户端需要能够连接到给定端口上的服务器地址 - 因此请考虑防火墙、路由等。

尽管如此,在这种情况下使用 Web 套接字并没有太多好处。您可以改用 AJAX,那么您就不必担心:

  • 防火墙设置在您身边
  • 代理服务器客户端
  • 自行管理多个连接
  • 序列化/反序列化
  • 支持 WebSockets 的目标浏览器平台

据我所知,WebSockets 的优势在于更低的延迟、更低的带宽和更好的控制。但是,如果这是一个拥有许多用户的真实应用程序,那么您最好在使用 WebSockets 解决方案之前让您的支持部门做好准备。

【讨论】:

  • 您可以在这里查看我的项目:github.com/Alxandr/Reverser。它对 websockets 有基本的支持,但我不知道这是否是最好的方法。我在一个单独的线程 from ASP.NET 上启动 websocket-server,所以它仍然在我认为的 IIS-worker 下运行,并且可以访问一些变量 xD。
  • @Alxandr:在 ASP.NET/IIS 下长时间运行的进程不是一件好事。工作进程应处理请求,然后尽快完成。
  • 是的,但它没有在线程池上运行。我制作了一个异步 http 处理程序,它同时处理 websocket 和长池请求。虽然我正在考虑使用 kayakhttp.com 之类的东西将它作为一个单独的服务器完全启动。
  • 也许我应该让 IIS 启动一个新进程...这样我就可以克服一些命令参数,也许还有一些基本的 IPC。
  • 理想/合适的解决方案是拥有一个 Windows 服务或长时间运行的控制台应用程序(Windows 服务更容易更好地管理、记录、启动、配置等),并在其中使用进程间通信必需(即 WCF、远程处理、命名管道等)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 2020-11-02
相关资源
最近更新 更多