当数据写入客户端的套接字时,服务器端没有收到数据

时间:2015-03-29 18:53:20

标签: perl sockets client server

我将“微笑从服务器”发送给客户,并希望客户“早上好”。基本上我不明白这个漏洞是在服务器端还是在客户端。 这是我的代码:

服务器端

#!/usr/bin/perl -w
# Filename : server.pl

use strict;
use Socket;

# use port 7890 as default
    my $port = shift || 7890;
    my $proto = getprotobyname('tcp');

    my $server = "localhost";  # Host IP running the server

# create a socket, make it reusable
    socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
       or die "Can't open socket $!\n";

# bind to a port, then listen
    bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
       or die "Can't bind to port $port! \n";

    listen(SOCKET, 5) or die "listen: $!";
    print "SERVER started on port $port\n";

# accepting a connection
    my $client_addr;
    while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
       # send them a message, close connection
       my $name = gethostbyaddr($client_addr, AF_INET );
       print NEW_SOCKET "Smile from the server";
       sleep(5);
       print <NEW_SOCKET>;
       print "Connection recieved from $name\n";
       close NEW_SOCKET;
 }

这是客户端:

#!/usr/bin/perl -w
    use strict;
    use Socket;
    # initialize host and port
    my $host = 'localhost';
    my $port = 7890;
    my $server = "localhost";  # Host IP running the server

    # create the socket, connect to the port
    socket(SOCKET,PF_INET,SOCK_STREAM,getprotobyname('tcp'))
       or die "Can't create a socket $!\n";

    connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
       or die "Can't connect to port $port! \n";

    my $line;
    while ($line = <SOCKET>) {
            print "$line\n";
            print SOCKET "good morning";
            sleep(10);
    }
    close SOCKET or die "close: $!";

2 个答案:

答案 0 :(得分:0)

缓冲

当您使用全局文件句柄和低级核心套接字函数而不是使用更高级别的IO::Handle派生时,很难展示如何关闭缓冲的示例socket wrapper。

如果您使用它,那么这很简单。然后服务器将是:

use strict;
use IO::Socket::IP;

# use port 7890 as default
my $port = shift || 7890;

my $listensock = IO::Socket::IP->new(
    LocalPort => $port,
    Listen => 5,
) or die "Cannot listen - $@";

# accepting a connection
while (my ($client, $client_addr) = $listensock->accept) {
    $client->autoflush(1);   ### THIS IS THE KEY LINE

    # send them a message, close connection
    $client->print("Smile from the server");
    sleep(5);

    print <$client>;
}

关键点是此处调用autoflush,它会禁用输出缓冲并确保立即发送所有字节。

答案 1 :(得分:0)

$ client-&gt; print(“来自服务器的微笑\ n”);

'\ n'是getline的结束ch