在 Python 和 Perl 套接字之间交换数据

Exchange data between Python and Perl sockets

同事用Perl写了一个简单的服务器,监听端口等待消息,然后发送响应:

#!/usr/bin/perl


use strict;
use IO::Select;
use IO::Socket::INET;

use constant SIZE => 1024;
use constant EOL => "\x0D\x0A";

my %user_input;

if(scalar @ARGV < 2)
{
die "Usage: server.pl ip port\n";
}

my ($serv_ip, $serv_port) = @ARGV;

my $socket = IO::Socket::INET->new(LocalAddr => $serv_ip, LocalPort => $serv_port, Listen => 20, Proto => 'tcp', Reuse => 1) or die $!;
my $select = IO::Select->new($socket) or die $!;

print "Started\n";

while(1)
      {
        my @r = $select->can_read;
        my @w = $select->can_write(.1);

      for my $handle (@r) {
                  if($handle eq $socket) {
                      my $connect = $socket->accept();
                      $select->add($connect);
                                          }
                      else {
                          my $user_input;
                          while(sysread $handle, $_, SIZE) {
                                  $user_input .= $_;
                                  last if $_ =~ /\x0A/ or length $user_input >= SIZE;
                                                        }
                                  printf ("Input:$user_input\n");
                                    if(length $user_input > 0) {
                                      $user_input = handle_request($user_input, $handle);
                                          if($user_input) {
                                             printf("Output:$user_input\n");
                                            syswrite $_, $user_input, SIZE for @w;
                                                          }
                                                } else {
                                             $select->remove($handle);
                                             close $handle;
                                                        }
                            }
                         }
        }

##################
sub handle_request
{
  my ($user_input, $handle) = @_;

my $error_begin = "Hello world!";
$error_begin .= EOL;

return $error_begin;
} 

别问了。我对珍珠不了解,害怕他。

我在 Python 3 上写了一个发送消息并等待响应的简单脚本:

import socket
import json

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect(('host', 9999))
data = 'message'
s.sendall(data.encode())

data = s.recv(1024)
print(data)

s.close()

当我 运行 它引发异常:

data = s.recv(1024)
socket.timeout: timed out

这意味着我的请求来了,而响应没有。但是我的同事在他的服务器上看到了我的请求。同时,我在 Python 上成功提交了与我自己的服务器的会话,并进行了类似的分配。此外,我可以通过 telnet 与我同事的服务器发送消息和接收答复。我怀疑 Python 和 Perl 中的默认套接字设置存在一些差异。 知道可能是什么问题吗?

更新: Perl 5.20.1 python3.4.2

哦!我讨厌这个!最初在服务器端是一个错误,产生了同样的效果。但是当它更正时,我忘记了服务器正在等待 \n 完成请求。