我从零开始使用perl创建了一个简单的websocket服务器,当通过echo测试在Chrome中连接时,出现错误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);
转换后(请注意此时的 $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);
使它工作。