尝试在 .NET 中设置 Web 套接字连接时遇到的麻烦 [英] woes in trying to set up a web socket connection in .NET
问题描述
我有我的 index.aspx 文件:
I have my index.aspx file:
<%@ 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?会是什么文件?(可能是一个愚蠢的问题,但因为它没有扩展名..)
and so basically i guess i will need to create a file that points to ws://localhost:14970/ws? What file would it be? (probably a stupid question, but since it doesn't have an extension..)
我从某个地方获得了这段代码,WebSocketServer.cs:
I've had this code from somewhere, 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
?
so now my question is how do i connect the WebSocketServer.cs
to the index.aspx
?
首先,我想要完成的只是让 Web Sockets 工作,并建立连接,然后 alert("Stock Ticker Connection open ...");
As a start, all I'm trying to accomplish is just to get the Web Sockets working, and have the connection established, which then will alert("Stock Ticker Connection open …");
推荐答案
WebSocketServer.cs 应该在单独的应用程序中运行,例如控制台应用程序或 Windows 服务.你调用 Start()
,它会监听来自客户端的连接.不涉及 ASP.NET.您可以使用常规的 HTML 页面:它是充当客户端的 Javascript 代码.
WebSocketServer.cs should be run in a separate application, e.g. console app or Windows Service. You call Start()
on that, and it listens for connections from clients. ASP.NET isn't involved. You could use a regular HTML page: it's the Javascript code that acts as the client.
您还需要考虑客户端需要能够连接到给定端口上的服务器地址 - 因此请考虑防火墙、路由等.
You'd also need to consider that clients will need to be able to connect to the server address on the port given - so think about firewalls, routing, etc.
就其价值而言,在这种情况下使用网络套接字并没有太多优势.你可以改用 AJAX,那么你就不用担心了:
For what it's worth there aren't many advantages to using a web socket in this case. You could use AJAX instead, then you wouldn't have to worry about:
- 防火墙为您设置
- 代理服务器在客户端
- 自己管理多个连接
- 序列化/反序列化
- 支持 WebSockets 的目标浏览器平台
据我所知,WebSockets 的优势是更低的延迟、更低的带宽和更好的控制.但是,如果这是一个拥有众多用户的真实应用,您最好在使用 WebSockets 解决方案之前让您的支持部门做好准备.
The advantage of WebSockets, as far as I can see, is a lower latency, lower bandwidth and greater control. But if this is a real-world app with many users you'd better get your support department in gear before using a WebSockets solution..
这篇关于尝试在 .NET 中设置 Web 套接字连接时遇到的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!