已建立 TCP 连接但套接字没有 send/recv 数据

Established TCP connection but socket doesn't send/recv data

我正在编写一个简单的 TCP 客户端和服务器 Perl 脚本。 截至目前,我使用 wireshark 验证了 3 次 TCP 握手,并建立了连接。 但是当我尝试发送或接收数据时,什么也没有发生。

问题:

1) 客户端和服务器之间的主要区别仅在于服务器添加了一个 LISTEN 参数,使其能够侦听传入连接?

2)接收和显示数据之间是否缺少任何步骤?

3)当程序第一次执行while循环时,至少应该发送硬编码字符串“$response”吗?

4)shutdown($sock,1) 和 sleep(1) 在此实现中有何不同?让套接字休眠可以吗,还是我应该使用 shutdown($sock,1) 向 client/server 发送数据已发送的信号?

在 wireshark 中检查连接状态时,我注意到只有握手发生。根本没有数据交换。所以我很确定问题出在写入套接字和从套接字读取数据(使用键盘或硬编码字符串)的某个地方。

任何帮助将不胜感激。

客户端如下:

#!/usr/bin/perl 
use IO::Socket;
use Getopt::Long;
#$IP_addr = $ARGV[0];
#$tgt_port = $ARG[1];

#netcat client

$port = 9040;
$sock = IO::Socket::INET->new( PeerAddr => 'localhost',
                               PeerPort => $port,
                               LocalPort => 9000,               
                               Proto     => 'tcp')
                               or die "\nunable to bind on localhost : $port...";

while ($sock){
    #Get the clients IP and port number 
        $client_IP = $sock -> peerhost();
    #$client_IP = 'localhost';
        $client_port = $sock -> peerport();
        print "\n Connected to $client_IP $client_port \n";

    #Reading from socket
    $data;  
    $sock ->recv($data, 1024);
    print $data;

    #writing to  socket
    $sock->autoflush(1);
    $response = "response: OK recvd\n" ;
    $sock->send($response);
    shutdown($sock,1);

}

$sock -> close();

服务器如下:

#!/usr/bin/perl 
use IO::Socket;
use Getopt::Long;

#$IP_addr = $ARGV[0];
#$tgt_port = $ARG[1];

#netcat server
$port = 9040;
$sock = IO::Socket::INET->new( Listen    => 1,
                               LocalAddr => 'localhost',
                               LocalPort => $port,
                               Proto     => 'tcp')
                               or die "\nunable to bind on localhost : $port...";

while ($sock){
    print "\nListening on port $port ...\n";
        $sock  = $sock -> accept();
    #Get the clients IP and port number 
        $client_IP = $sock->peerhost();
        $client_port = $sock->peerport();
        print "\n Connected from $client_IP $client_port \n";

    #Reading from socket
    $data ->recv($sock, 1024);
    print $data;

    #writing to  socket
    $sock->autoflush(1);
    $response = "oohlalala" ;
    $sock -> send($response);
    shutdown($sock, 1);

}

$sock -> close();

服务器代码(使用 telnet localhost 9040 测试):

use strict;
use warnings;

use IO::Socket::INET;

my $port = 9040;
my $listen = IO::Socket::INET->new(Listen    => 1,
                                   LocalPort => $port,
                                   Proto     => 'tcp',
                                   ReuseAddr => 1,
                                   ReusePort => 1);
while ($listen) {
    print "\nListening on port $port ...\n";
    my $sock  = $listen->accept();
    my $client_IP = $sock->peerhost();
    my $client_port = $sock->peerport();
    print "\n Connected from $client_IP $client_port \n";

    my $data;
    $sock->recv($data, 1024);
    print $data;

    #writing to  socket
    $sock->autoflush(1);
    my $response = "oohlalala\n" ;
    $sock->send($response);
    shutdown($sock, 1);
}

客户端代码(针对上述服务器进行测试):

use strict;
use warnings;

use IO::Socket::INET;

my $port = 9040;
my $sock = IO::Socket::INET->new(PeerAddr  => 'localhost',
                                 PeerPort  => $port,
                                 Proto     => 'tcp');

if ($sock) {
    my $server_IP = $sock->peerhost();
    my $server_port = $sock->peerport();
    print "\n Connected to $server_IP $server_port \n";

    # initiate protocol
    $sock->autoflush(1);
    print $sock "OK\n";

    my $data;
    $sock->recv($data, 1024);
    print $data;

    shutdown($sock, 1);
}

服务器输出:

Listening on port 9040 ...

 Connected from 127.0.0.1 36106 
OK

Listening on port 9040 ...

来自客户端的输出:

 Connected to 127.0.0.1 9040 
oohlalala

来自 IO::Socket

As of VERSION 1.18 all IO::Socket objects have autoflush turned on by default. This was not the case with earlier releases.

Perl 2.0 版于 1988 年发布。您最有可能使用的是 perl 版本 5.x。

1) the major difference between the client and the server is only that the server has an added LISTEN parameter which enables it to listen for incoming connections ?

根据 docs:

If Listen is defined then a listen socket is created...

监听套接字可以调用accept()。如果常规套接字调用 accept(),accept() returns undef.

accept()

In a scalar context the new socket is returned, or undef upon failure. In a list context a two-element array is returned containing the new socket and the peer address; the list will be empty upon failure.

https://perldoc.perl.org/IO/Socket.html

这里是nice, short, basic description of sockets.

您的服务器代码可能隐藏了一些正在发生的事情。如果这样写就更能说明问题了:

$server_socket = IO::Socket::INET(.....);
...
...
my $client_socket = $server_socket->accept();
...
...

有两个不同的插座。 accept() return 为服务器和客户端通信的新套接字,因此原始服务器套接字可以继续侦听客户端连接。

2) Are there any steps missing between recv and displaying the data?

根据您正在做的事情,您可能想要去掉标记数据结尾的字符,代码会使用这些字符来向另一端发出停止尝试读取更多数据的信号从套接字。

接收数据是棘手的部分。客户端和服务器必须使用商定的协议以避免死锁,即客户端和服务器都在等待另一方发送数据。在下面的示例中,我使用了 "line oriented" 协议,其中一侧在读取换行符时停止从套接字读取。在网络中,按照惯例,换行符被认为是“\r\n”,它代表 ascii 字符 carriage returnline feed,但为了避免在各种情况下进行任何类型的自动“\n”转换OS's,套接字库使用实际的 ascii 代码:13 和 10,十六进制表示法是:“\x0D\x0A”。

server.pl:

use strict;  
use warnings; 
use 5.020;
use autodie;
use Data::Dumper;

use IO::Socket::INET;
use Socket qw( :crlf );  # "\x0D\x0A" constants CRLF and $CRLF

my $host = 'localhost';
my $port = 15_678;

my $server_socket = IO::Socket::INET->new(
        Listen    => 5,
        LocalPort => $port,
        LocalAddr => $host,
        Proto     => 'tcp',
        ReuseAddr => 1,
        ReusePort => 1
);

say "Server listening on port: $port\n";

while (my $client_socket = $server_socket->accept() ) {

    my $client_ip = $client_socket->peerhost();
    my $client_port = $client_socket->peerport();
    say "Connection from $client_ip:$client_port";

    {
        local $/ = CRLF; # $/ is the input record separator, which is "\n" 
                         #by default. Both <$INFILE> and getline() read up to
                         #and including the input record separator.
        while(my $line = $client_socket->getline) { #Blocks until CRLF is read 
                                                 #from the socket or the other 
                                                 #side closes the socket.
            chomp $line; #chomp() removes input record separator from end of line.
            say "Server received: $line";

            my $response = reverse $line;
            $client_socket->send("$response$CRLF");

            say "Server sent: $response";
        }

    }  #Here $/ is restored to whatever it was before this parenthesized block. 
       #That is what declaring a variable as local does.

    say "-" x 30;

    #Execution arrives here after the client closes the socket:
    $client_socket->shutdown(2);  #Send signals to other side of socket.
                                  #Not necessary in this example because other threads  
                                  #aren't also reading from the socket.
    $client_socket->close();  #Close the filehandle associated with the socket.
}

请注意,就像读取文件时一样,getline 将 return 在接收到 eof 信号时它已读取的所有内容,而对于 while 循环的下一次迭代,getline 将 return undef 导致 while 循环终止。

client.pl:

use strict;  
use warnings; 
use 5.020;
use autodie;
use Data::Dumper;

use IO::Socket::INET;
use Socket qw( :crlf ); #\x0D\x0A constants CRLF and $CRLF 

my $port = 15_678;

my @lines = (
    "hello world",
    "goodbye mars",
);

my $sock = IO::Socket::INET->new("localhost:$port");

for my $line(@lines){

    my $server_ip = $sock->peerhost();
    my $server_port = $sock->peerport();
    say "Connected to $server_ip:$server_port";

    $sock->send("$line$CRLF");
    say "Client sent: $line";

    my $response;
    {
        local $/ = CRLF;
        $response = $sock->getline();
        chomp $response;
    }  

    say "Client received: $response";
    say '-' x 30;

}

#Tell the server that no more data is coming from this client:
$sock->shutdown(2);  #Send signals to other side of socket.
$sock->close();  #Close the filehandle associated with the socket.

在运行客户端程序两次后...

服务器输出:

Server listening on port: 15678

Connection from 127.0.0.1:56085
Server received: hello world
Server sent: dlrow olleh
Server received: goodbye mars
Server sent: sram eybdoog
------------------------------
Connection from 127.0.0.1:56096
Server received: hello world
Server sent: dlrow olleh
Server received: goodbye mars
Server sent: sram eybdoog
------------------------------

客户端输出:

$ perl client.pl 
Connected to 127.0.0.1:15678
Client sent: hello world
Client received: dlrow olleh
------------------------------
Connected to 127.0.0.1:15678
Client sent: goodbye mars
Client received: sram eybdoog
------------------------------
$ perl client.pl 
Connected to 127.0.0.1:15678
Client sent: hello world
Client received: dlrow olleh
------------------------------
Connected to 127.0.0.1:15678
Client sent: goodbye mars
Client received: sram eybdoog
------------------------------
$ 

3) Shouldn't atleast the hardcoded string "$response" be sent when the program executes the while loop the first time?

是的,while 循环中的所有语句都将在第一个循环完成执行后执行——但是当循环中更高层的语句阻塞时,发送永远不会执行。

4) How do shutdown($sock,1) and sleep(1) differ in this implementation? Is it okay to let the socket sleep or should I use shutdown($sock,1) to signal to the client/server that data has been sent ?

我不确定 shutdown() 和 sleep() 之间有何关联。 sleep() 会在指定时间内停止执行代码,而 shutdown() 会将某些内容发送到套接字的另一端。

"Closing the socket",即调用shutdown(),来标记数据的结束是另一种可以采用的协议。它使事情变得非常简单:一侧只是继续以某种读取语句从套接字中读取,而当另一侧关闭套接字时,读取将 return。这是一个例子:

server.pl:

use strict;  
use warnings; 
use 5.020;
use autodie;
use Data::Dumper;

use IO::Socket::INET;

my $host = 'localhost';
my $port = 15_678;

my $server_socket = IO::Socket::INET->new(
        Listen    => 5,
        LocalPort => $port,
        LocalAddr => $host,
        Proto     => 'tcp',
        ReuseAddr => 1,
        ReusePort => 1
);

say "Server listening on port: $port\n";

while (my $client_socket = $server_socket->accept() ) {

    my $client_ip = $client_socket->peerhost();
    my $client_port = $client_socket->peerport();
    say "Connection from $client_ip:$client_port";

    my $data;
    {
        local $/ = undef;  #This input record separtor will never be found...
        $data = <$client_socket>;  #...so this reads everything--including newlines--until it gets an eof signal.
    }

    say "Server received: $data";
    my $response = reverse $data;
    $client_socket->send($response);

    $client_socket->shutdown(2); #Doesn't close filehandle -- merely sends signals.
    $client_socket->close();  ##Close the filehandle associated with the socket.

    say "Server sent: $response";
    say "-" x 30;
}

client.pl:

use strict;  
use warnings; 
use 5.020;
use autodie;
use Data::Dumper;

use IO::Socket::INET;

my $port = 15_678;

my @data = (
    "hello \n world",   #Now newlines are in the data
    "goodbye \n mars",
);

for my $data (@data){
    my $sock = IO::Socket::INET->new("localhost:$port");
    my $server_ip = $sock->peerhost();
    my $server_port = $sock->peerport();
    say "Connected to $server_ip:$server_port";

    $sock->send($data);
    say "Client sent: $data";
    $sock->shutdown(1);

    my  $response;
    { 
        local $/ = undef;  #This input record separtor will never be found...
        $response = <$sock>;  ##...so this reads everything--including newlines--until it gets an eof signal.
    }
    $sock->shutdown(0);

    $sock->close();

    say "Client received: $response";
    say '-' x 30;

}

服务器输出:

Server listening on port: 15678

Connection from 127.0.0.1:53139
Server received: hello 
 world
Server sent: dlrow 
 olleh
------------------------------
Connection from 127.0.0.1:53140
Server received: goodbye 
 mars
Server sent: sram 
 eybdoog
------------------------------

客户端输出:

Connected to 127.0.0.1:15678
Client sent: hello 
 world
Client received: dlrow 
 olleh
------------------------------
Connected to 127.0.0.1:15678
Client sent: goodbye 
 mars
Client received: sram 
 eybdoog
------------------------------