socket send

Francesco Bochicchio bieffe62 at gmail.com
Thu Jul 30 06:29:24 EDT 2009


On Jul 30, 5:52 am, NighterNet <darkne... at gmail.com> wrote:
> I am trying to figure out how to send text or byte in python 3.1. I am
> trying to send data to flash socket to get there. I am not sure how to
> work it.
>
> buff= 'id=' , self.id , ':balive=False\n'
> clientSock.send(buff);

Try putting a 'b' before the constant string that you want to send:

>>> type(b'123')
<class 'bytes'>

or use something like this to convert non constant strings (with only
ASCII characters) into bytes:

>>> s = "A non-constant string : %d " % n
>>> s
'A non-constant string : 12 '
>>> type(s)
<class 'str'>
>>> b = bytes ( ord(c) for c in s )
>>> b
b'A non-constant string : 12 '

You could also use struct.pack , that in python 3.x returns bytes and
not strings. In this case you need to specify the size of the string
(extra
bytes are zero-filled):

import struct

>>> struct.pack( "30s", "A non-constant string : %d " % n )
b'A non-constant string : 12 \x00\x00\x00'



Ciao
-----
FB



More information about the Python-list mailing list