socket script from perl -> python
kettle
Josef.Robert.Novak at gmail.com
Thu Feb 7 09:39:26 EST 2008
Hi I have a socket script, written in perl, which I use to send audio
data from one server to another. I would like to rewrite this in
python so as to replicate exactly the functionality of the perl
script, so as to incorporate this into a larger python program.
Unfortunately I still don't really have the hang of socket programming
in python. The relevant parts of the perl script are below:
$host = '127.0.0.1';
my $port = 3482;
my $proto = getprotobyname('tcp');
my $iaddr = inet_aton($host);
my $paddr = sockaddr_in($port, $iaddr);
# create the socket, connect to the port
socket(SOCKET, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
connect(SOCKET, $paddr) or die "connect: $!";
my $length = length($converted_audio);
# pack $length as a 32-bit network-independent long
my $len = pack('N', $length);
#print STDERR "LENGTH: $length\n";
SOCKET->autoflush();
print SOCKET "r";
print SOCKET $len;
print SOCKET "$converted_audio\n";
while(defined($line = <SOCKET>)) {
....do something here...
}
------------
I've used python's socket library to connect to the server, and
verified that the first piece of data'r' is read correctly, the
sticking point seems to be the $len variable. I've tried using
socket.htonl() and the other less likely variants, but nothing seem to
produce the desired result, which would be to have the server-side
message print the same 'length' as the length printed by the client.
The python I've tried looked like this:
from socket import *
host = '127.0.0.1'
port = 3482
addr = (host, port)
s = socket(AF_INET, SOCK_STREAM)
s.connect(addr)
f = open('/home/myuname/socket.wav','rb')
audio = ""
for line in f:
audio += line
leng = htonl(len(audio))
print leng
s.send('r')
s.send(leng)
s.send(audio)
s.send("\n")
s.flush()
----------------------
of course I'd also like to s.recv() the results from the server, but
first I need to properly calculate the length and send it as a network
independent long. Any tips on how to do this would be greatly
appreciated!
More information about the Python-list
mailing list