I am making a chat client to connect to a server I already made with sockets in Python 3, but I am having a problem with the new encoding and decosing stuff for Python 3. Here is the relevant code:

else :
    # user entered a message
    msg = sys.stdin.readline()
    s.send(bytes((msg, 'utf-8')))
    sys.stdout.write(bytes('[Me] '))
    sys.stdout.flush()

and here is the error I get when running this client from python in terminal:

# It connects to the server fine, as we can see from the next two lines, but if I try to type a message it closes and outputs the error message.
Connected to remote host. You can start sending messages
[Me] hi
Traceback (most recent call last):
  File "client.py", line 50, in <module>
    client()
  File "client.py", line 45, in client
    s.send(bytes((msg, 'utf-8')))
TypeError: 'str' object cannot be interpreted as an integer

I read this: http://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/ and adjusted my code accordingly, but it still gives me the same error. Please feel free to ask for anything else you may need.

The signature of the bytes() function gives the solution

class bytes(object)
 |  bytes(iterable_of_ints) -> bytes
 |  bytes(string, encoding[, errors]) -> bytes
 |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
 |  bytes(int) -> bytes object of size given by the parameter initialized with null bytes
 |  bytes() -> empty bytes object
...

You want to use the second form bytes(string, encoding) but instead you wrote bytes((string, encoding)), that is to say a single tuple argument. Since a tuple is iterable, the only option for python is to believe that you used the first form. Then python expects that your tuple is a tuple of ints, and as this fails, you get the error. So use

bytes(msg, 'utf-8')
commented: Great knowledge. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.