【问题标题】:Server side socket program not working in PERL服务器端套接字程序在 PERL 中不起作用
【发布时间】:2016-06-06 15:19:56
【问题描述】:

我在 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();

【问题讨论】:

    标签: perl sockets


    【解决方案1】:

    您的套接字创建可能没有任何问题。您的打印语句可能会被缓冲。要么在打印语句的末尾添加一个新行字符,要么在脚本的开头设置$|=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();
    

    【讨论】:

    • 谢谢克里斯。我继续使用您提供的强制刷新解决方案。现在我的服务器正在等待客户端,但似乎有一些问题。请看我的客户程序:
    • 谢谢克里斯。我继续使用您提供的强制刷新解决方案。现在我的服务器正在等待客户端,但似乎有一些问题。请看我的客户程序:使用严格;使用警告;使用 IO::Socket::INET; $|=1;我的($socket,$client_socket); #Socket 创建 $socket = new IO::Socket::INET(PeerHost=>'127.0.0.1',PeerPort=>'5000',Proto=>'tcp',Listen=>5) or die "Error in Socket Creation : $!n"; print "打印 TCP 连接成功"; #读取服务器发送的数据 my $data = ; print "从服务器接收到:$data\n"; $socket->close();
    • 客户端程序执行与服务器等待连接的输出是:打印 TCP 连接成功使用未初始化的值 $data 连接 (.) 或 ClientSocket.pl 第 18 行的字符串。从服务器接收:
    • 要读取套接字上的数据,您需要使用套接字recv 方法。因此,如果您想读取接下来的 1024 字节数据,您应该使用 $socket->recv( my $data, 1024); 这将从套接字读取 1024 字节并将其存储在 $data 变量中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多