gpt4 book ai didi

perl - 从头开始的简单 websocket 服务器不起作用

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

从头开始使用 perl 创建一个简单的 websocket 服务器,当从 Chrome 指向它时(通过使用 echo test),得到错误 Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value .

很确定为 websocket 握手返回的 key 是正确的。有任何想法吗?

use IO::Socket;
use IO::Select;
use Digest::SHA1 qw(sha1 sha1_hex sha1_base64);


$servSock = IO::Socket::INET->new( Proto => 'tcp',
LocalPort => 8080,
Reuse => 1,
Listen => 500
) || die "failed to setup outsock $@\n";
$s = IO::Select->new();
$s -> add ($servSock);
my @readySocks;
while (1) {
@readySocks = $s->can_read(5);
foreach $sock (@readySocks) {
if ($sock eq $servSock)
{
#print "inSock\n";
$clientSock = $servSock->accept();
setsockopt($clientSock, IPPROTO_TCP, TCP_NODELAY, 1);
$s->add ($clientSock);
} else
{
#print "outsock\n";
$buff = "";
$fromAddr = recv $sock, $buff, 1470, 0;
if (length($buff) <= 0)
{
$s->remove($sock);
close $sock; $numOfConns --;
next;
}
printf "recved %d bytes\n", length($buff);
if ($buff =~ /Sec-WebSocket-Key: (\S+)/) {
$str = $1;
print "key is $str|\n";
my $str = sha1_base64($str . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
send ($sock, qq{HTTP/1.1 101 Switching Protocols\r
Connection: Upgrade\r
Upgrade: websocket\r
Sec-Websocket-Accept: $str\r
\r\n}, 0);
}
}
}
}

注意:我需要从头开始创建一个作为另一个项目的一部分。

更新

感谢@steffen-ullrich 的建议,将其从
send ($sock, qq{HTTP/1.1 101 Switching Protocols\r
Connection: Upgrade\r
Upgrade: websocket\r
Sec-Websocket-Accept: $str\r
\r\n}, 0);

到(注意这里 $str 现在是 $str=)
send ($sock, qq{HTTP/1.1 101 Switching Protocols\r
Connection: Upgrade\r
Upgrade: websocket\r
Sec-Websocket-Accept: $str=\r
\r\n}, 0);

使它工作。

最佳答案

来自 documentation of sha1_bas64 :

Note that the base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded sha1 digests you might want to append the redundant string "=" to the result.



并按照描述添加 '=' 是您的代码所缺少的。

关于perl - 从头开始的简单 websocket 服务器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42523419/

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