Trimax
Trimax

Reputation: 2473

Sockets in windows

I wrote an example of programming sockets in Python.

# Prueba Sockets -Cliente-
import socket

s = socket.socket()
s.connect(("localhost", 9999))

while True:
      message = input("Enter the message: ")
      s.send(message)
      if message == "quit":
         break

print("Good bye")

s.close()

a = input("Enter key to End:")

While the server script is running I'd run the client script but it throws an error.

This is the output:

Enter the message: Try this.
Traceback (most recent call last):
  File "C:/Users/sajime/PycharmProjects/Learning/SocketClient.py", line 9, in <module>
    s.send(message)
TypeError: 'str' does not support the buffer interface

Python 3.3 in Windows 7.

I'd tried with an integer instead the string, but it throws error too.

When the client stops by error the server goes to an endless loop printing empty messages.

Upvotes: 0

Views: 1437

Answers (2)

Nico
Nico

Reputation: 6913

Try this :

s.send(bytes(message, "UTF-8"))

Just like @falsetru said, the python 3.x api changed. You now need to send bytes instead of a string.

Upvotes: 1

falsetru
falsetru

Reputation: 369494

In Python 3.x, socket.send accepts bytes object instead of str object. Encode the string.

Replace the following line:

s.send(message)

with:

s.send(message.encode())

Upvotes: 1

Related Questions