0

According to the docs, Python's socket.send():

Returns the number of bytes sent.

However, when I use it, it seems to return the byte that was last sent, not the total number of bytes sent. Consider this code:

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('localhost', 12345))
>>> r = s.send(bytes(1))
>>> print(r)
1
>>> r = s.send(bytes(15))
>>> print(r)
15
>>> r = s.send(bytes(150))
>>> print(r)
150
>>> r = s.send(bytes(255))
>>> print(r)
255
>>> r = s.send(bytes(0))
>>> print(r)
0

This SO post seems related, though it doesn't answer my question.

What I'm expecting to see is r == 1 for every line.

Solved:

I got it. This works:

>>> y = bytearray(1)
>>> y[0] = 125
>>> r = s.send(y)
>>> print(r)
1

The reason I put bytes() in there to begin with is because without it you get:

>>> r = s.send(125)
TypeError: a bytes-like object is required, not 'int'
boardrider
  • 5,882
  • 7
  • 49
  • 86
101010
  • 14,866
  • 30
  • 95
  • 172

2 Answers2

3

As the docs for bytes say, if the argument is an integer, then it creates a bytearray of that size.

https://docs.python.org/3.1/library/functions.html#bytes https://docs.python.org/3.1/library/functions.html#bytearray

Maybe this is what you meant to do?

In [26]: r = s.send(b'250')

In [27]: r
Out[27]: 3

But even then b'250' returns 3.

Cory Madden
  • 5,026
  • 24
  • 37
0

The confusion is how Python 2.x and Python 3.x use the bytes() function.

In Python3, bytes(100) will evaluate to a 100 byte binary array filled in with zero. (API docs) This must be the version of Python you're running as this behavior is consistent with your output.

In Python2, bytes(100) will evaluate to '100'. It converts the integer into a string and then assigns the bytearray to that value. Doing help(bytes) on it shows that it is actually the same as the built-in object str. So in Python2 bytes(100) behaves the same as str(100).

Also in your examples, even according to your expected Python2 behavior, the return value would not always be 1. It would be the length of the string, which would be the same as the number of digits in the integer, e.g. 3 for the case of bytes(100).

MrJLP
  • 978
  • 6
  • 14