使用perl从头开始创建一个简单的websocket服务器,当从Chrome指向它时(使用echo test),得到错误Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value
。
非常确定为websocket握手返回的密钥是正确的。有什么想法吗?
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);
to(注意$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);
让它发挥作用。
答案 0 :(得分:5)
来自documentation of sha1_bas64:
请注意,返回的base64编码字符串未填充为4个字节长的倍数。如果您想要与其他base64编码的sha1摘要进行互操作,您可能希望将冗余字符串“=”附加到结果。
如上所述添加“=”是您的代码缺失的原因。