gpt4 book ai didi

sockets - 区分 TcpClient 和 WebSocket?

转载 作者:行者123 更新时间:2023-12-03 12:00:27 25 4
gpt4 key购买 nike

我正在开发一个应用程序,其中我使用套接字在服务器应用程序和客户端应用程序(Web 和桌面两者)之间进行通信。我的服务器应用程序不断监听客户端应用程序的请求,并随时接受请求。
服务器代码:

TcpListener listener = new TcpListener(IPAddress.Parse(ipAddStr), portNum);
listener.Start();
while (listen)
{
TcpClient handler = listener.AcceptTcpClient();
// doing some stuff
// for every client handler i am creating a new thread and start listening for the next request
}

对于 Web 客户端,我使用的是 WebSocket,至于与 WebSocket 客户端建立连接,我们必须遵循一些握手过程。为此,我正在使用以下代码(工作正常):
    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private static string AcceptKey(ref string key)
{
string longKey = key + guid;
SHA1 sha1 = SHA1CryptoServiceProvider.Create();
byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
return Convert.ToBase64String(hashBytes);
}

生成和发送响应与 websocket 客户端握手:
       // generate accept key fromm client header request
var key = headerRequest.Replace("ey:", "`")
.Split('`')[1]
.Replace("\r", "").Split('\n')[0]
.Trim();
var responseKey = AcceptKey(ref key);

//create the response for the webclient
var newLine = "\r\n";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + responseKey + newLine + newLine;

//send respose to the webclient
Byte[] sendBytes = Encoding.ASCII.GetBytes(response);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();

我也有 TcpClient用于桌面应用程序的套接字,所以问题是如何识别请求来自 WebSocket或来自 TcpClient ?

最佳答案

最简单的方法是让 websocket 监听器和 vanilla TCP 监听器监听不同的端口号。无论如何你都应该这样做,因为 websocket 应用程序通常在标准 http 端口 80 上运行。 (或标准 https 端口 443 当您使用带有 TLS 的 websockets 时),而基于 TCP 的自定义协议(protocol)应在 1024 到 49151 之间的“注册”范围内的端口之一上运行。建议您遵循这一点,因为安全良好的客户端环境允许 Web 访问,但不允许用户连接到 80 和 443 以外的其他端口,而这些端口上的任何非 http 流量都可能触发入侵检测系统。

当您出于某种原因仍想在同一个端口上处理两种协议(protocol)时,会有些困难。 Websocket 是一个基于 TCP 的协议(protocol),一开始看起来像一个普通的 HTTP GET 请求,直到你收到头 Connection: UpgradeUpgrade: websocket .

这意味着对于任一协议(protocol)的连接请求首先需要被同一个监听器接受。只有在客户端发送了足够的数据以将其连接尝试识别为您的自定义协议(protocol)或 websocket(或完全不同的东西,意外连接到您的端口 - 当您部署面向互联网的应用程序时,您会遇到很多)然后委托(delegate)与客户端通信到适当的处理程序类。

关于sockets - 区分 TcpClient 和 WebSocket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26032968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com