【发布时间】:2018-02-11 20:21:50
【问题描述】:
我创建了一个在我的服务器上打开一个新套接字的 Perl 脚本。 当我通过 telnet 连接到套接字并写入(和接收)某些内容时,连接将关闭。
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;
use IO::Socket::INET;
$| = 1;
my $sock = IO::Socket::INET->new(Listen => 5,
LocalAddr => 'localhost',
LocalPort => 9000,
Reuse => 1,
Proto => 'tcp');
die "Socket not created $!\n" unless $sock;
print "Server waiting for connections\n";
while(1)
{
# waiting for a new client connection
my $client_socket = $sock->accept();
# get information about a newly connected client
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
print "Connection from $client_address:$client_port\n";
# read up to 1024 characters from the connected client
my $data = "";
$client_socket->recv($data, 1024);
chomp($data);
print "Data: $data\n";
# write response data to the connected client
my $dataok = "OK";
$client_socket->send("$dataok\n");
$client_socket->send("$data\n");
if($data == 500){
close($sock);
exit();
}
elsif($data eq "Close\r") {
close($sock);
exit();
}
}
我的远程登录会话:
telnet localhost 9000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
e //(Sent)
e //(Received)
Connection closed by foreign host.
为什么我的脚本会关闭连接? 提前致谢
【问题讨论】:
-
不是问题,但是当您的数据包含非数字字符时,您需要使用
eq,而不是==。 -
是的,我知道。我把它固定在我的机器上。
-
您有什么建议可以解决我的问题吗? @simbabque
-
请edit 然后更新问题。总是向我们展示你的真实代码,这样你就不会在一个不属于你的问题上浪费别人的时间;)
-
接受后,你读了一些东西,写了一些东西,然后你在循环中的块就完成了。这意味着客户端文件描述符超出了关闭套接字的范围。如果你想在同一个连接上多次读写,你必须围绕这个读写循环。
标签: perl sockets network-programming