TCP:python客户端和perl服务器 - 逐行接收

时间:2016-07-27 06:09:22

标签: python perl sockets tcp

perl_server.pl

computed

python_client.py

use IO::Socket::INET;
use Sys::Hostname;
use Socket;


my($addr)=inet_ntoa((gethostbyname(hostname))[4]);



# auto-flush on socket
$| = 1;

# creating a listening socket
my $socket = new IO::Socket::INET (
    LocalHost => $addr,
    LocalPort => '7777',
    Proto => 'tcp',
    Listen => 5,
    Reuse => 1
);
die "cannot create socket $!\n" unless $socket;
print "server waiting for client connection on $addr:7777\n";


# waiting for a new client connection
my $client_socket = $socket->accept();

# get information about a newly connected client
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
print "connection from $client_address:$client_port\n";
while(1)
{
    # read up to 1024 characters from the connected client
    my $data = "";
    $client_socket->recv($data, 1024);
    print "received data: $data\n";

    if ($data eq "done") {
        last;
    }else {
        # write response data to the connected client
        $data = "ok";
        $client_socket->send($data);
    }

}



# notify client that response has been sent
shutdown($client_socket, 1);
$socket->close();

所以,上面的代码工作正常,但我希望import socket import sys import time # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = ('0.0.0.0', 7777) print >>sys.stderr, 'connecting to %s port %s' % server_address sock.connect(server_address) cnt = 0 while True: try: cnt += 1 #time.sleep(1) # Send data message = 'This is the message. It will be repeated.' print >>sys.stderr, 'sending "%s"' % message sock.sendall(message) if cnt > 10000: sock.sendall("done") break except Exception, msg: continue print >>sys.stderr, 'closing socket' sock.close() 一次收到一行

例如,现在是以下代码,

perl_client.pl

$client_socket->recv($data, 1024); print "received data: $data\n"; 包含多行$data
我希望'This is the message. It will be repeated.'包含一行$data

现在来自客户端的这条消息可能会改变,所以我不知道如果只是改变1024就足够了。

有什么建议吗?

0 个答案:

没有答案