服务器端套接字程序在PERL中不起作用

时间:2016-06-06 06:03:04

标签: perl sockets

我在PERL中创建了一个简单的Socket程序。服务器端程序似乎没有完成套接字创建。它在Socket创建后不会打印语句。客户端等待来自服务器的消息然后关闭套接字。在打印Socket时,它获取Server套接字的引用,但不执行任何操作。请在下面找到简单的服务器和客户端程序。

服务器端程序:

#!usr/bin/perl
#tcpserver.pl

use IO::Socket::INET;

my($socket,$client_socket);

my($peeraddress,$peerport);

#Socket creation
$socket  = new IO::Socket::INET(LocalHost=>'127.0.0.1',LocalPort=>'5000',Proto=>'tcp',Listen=>5) or die "Error in Socket Creation: $!n";

print "Server Waiting for client connection on port 5000";

while(1)
{   
    $client_socket = $socket->accept();

    $peer_address = $client_socket->peerhost();

    $peer_port = $client_socket->peerport();

    print "Accepted New Client Connection From : $peer_address $peer_port\n";

    #Send message to the client 

    $data = "Message from Server";

    $client_socket->send($data);

}

$socket->close();

1 个答案:

答案 0 :(得分:1)

您的套接字创建可能没有任何问题。机会是你的打印声明它被缓冲。在print语句的末尾添加一个新的行char或在脚本的开头设置$|=1;以强制Perl刷新打印语句而不缓冲它。

也是在代码中使用严格和警告的好习惯。

use strict;
use warnings;
use IO::Socket::INET;
$|=1;

my($socket,$client_socket);
my($peeraddress,$peerport);

#Socket creation
$socket  = new IO::Socket::INET(LocalHost=>'127.0.0.1',LocalPort=>'5000',Proto=>'tcp',Listen=>5) or die "Error in Socket Creation: $!n";

print "Server Waiting for client connection on port 5000";

while(1)
{
    my $client_socket = $socket->accept();
    my $peer_address = $client_socket->peerhost();
    my $peer_port = $client_socket->peerport();
    print "Accepted New Client Connection From : $peer_address $peer_port\n";

    #Send message to the client
    my $data = "Message from Server";
    $client_socket->send($data);
}

$socket->close();