socket send help

Chris Rebert clp at rebertia.com
Wed Dec 24 01:43:19 EST 2008


On Tue, Dec 23, 2008 at 9:59 PM, greywine at gmail.com <greywine at gmail.com> wrote:
> Hi everyone,
>
> New guy here.  I'm trying to figure out sockets in order to one day do
> a multiplayer game.  Here's my problem:  even the simplest examples
> don't work on my computer:
>
> A simple server:
>
> from socket import *
> myHost = ''
> myPort = 21500
>
> s = socket(AF_INET, SOCK_STREAM)    # create a TCP socket
> s.bind((myHost, myPort))            # bind it to the server port
> s.listen(5)                         # allow 5 simultaneous connections
>
> while True:
>    connection, address = s.accept()
>    while True:
>        data = connection.recv(1024)
>        if data:
>            connection.send('echo -> ' + data)
>        else:
>            break
>    connection.close()              # close socket
>
> And a simple client:
>
> import sys
> from socket import *
> serverHost = 'localhost'            # servername is localhost
> serverPort = 21500                  # use arbitrary port > 1024
>
> s = socket(AF_INET, SOCK_STREAM)    # create a TCP socket
>
>
> s.connect((serverHost, serverPort)) # connect to server on the port
> s.send('Hello world')               # send the data
> data = s.recv(1024)                 # receive up to 1K bytes
> print(data)
>
>
> If I run testserver.py via the cmd prompt in Windows XP and then the
> testclient.py program, I get the following error:
>
> Traceback (most recent call last):
>  File "C:\Python30\testclient.py", line 12, in <module>
>    s.send('Hello world')               # send the data
> TypeError: send() argument 1 must be string or buffer, not str
>
> This happens in 2.6 or 3.0 and with different example client & server
> programs from the web.  What am I missing?

The text of the error message seems outdated (it should probably say
"bytes or bytearray" instead of "string or buffer"), but what it's
trying to say is that you can only send() bytes, not unicode strings.
For a byte literal, you need to add a 'b' prefix, e.g. b'Hello World'
Alternatively, you can encode the unicode into bytes using .encode(),
e.g. "Hello World".encode('utf8')

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list