user3089646
user3089646

Reputation: 23

Cannot Get Strings Across in a Socket Program

I have been looking at some code for a small chat program that I found online. It was originally written for 2.7, but it seems to work with 3.2. The only problem is that I cannot send strings, only numbers:

The chat.py file source code:

from socket import *
HOST = ''
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1) 
conn, addr = s.accept() 
print ('Connected by ' + str(addr)) 
i = True
while i is True:
    data = conn.recv(1024)
    print ("Received " + repr(data))
    reply = str(input("Reply: "))
    conn.send(reply)
conn.close()

And the client.py source file:

from socket import * 
HOST = ''
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT)) # client-side, connects to a host
while True:
    message = str(input("Your Message: "))
    s.send(message)
    print ("Awaiting reply...")
    reply = s.recv(1024) # 1024 is max data that can be received
    print ("Received " + repr(reply))
s.close()

When I run these using two separate terminals, they work, but do not send strings.

Thank you

Upvotes: 2

Views: 341

Answers (2)

woozyking
woozyking

Reputation: 5220

When you work with sockets, the message you're passing around should probably be in bytes, b'bytes'. In Python 2.x, a str is actually what a bytes is in Python 3.x

So your message should be something like:

message = b'Message I want to pass'

Check here http://docs.python.org/3.3/library/stdtypes.html for more information.

According to http://docs.python.org/3/library/functions.html#input input returns a str, which means you'll have to encode message into bytes as such:

message = message.encode()

Do verify that this is the right approach to convert str to bytes by checking the type of message.

Upvotes: 2

Stephen Diehl
Stephen Diehl

Reputation: 8409

Your socket code is correct, it was just failing due to an unrelated error due to raw_input vs input. You probably intended to read a string from the shell instead of reading a string and trying to evaluate it as Python code which is what input does.

Try this instead:

chat.py

from socket import *
HOST = ''
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1) 
conn, addr = s.accept() 
print ('Connected by ' + str(addr)) 
i = True
while i is True:
    data = conn.recv(1024)
    print ("Received " + repr(data))
    reply = str(raw_input("Reply: "))
    conn.send(reply)
conn.close()

client.py

from socket import * 
HOST = ''
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT)) # client-side, connects to a host
while True:
    message = str(raw_input("Your Message: "))
    s.send(message)
    print ("Awaiting reply...")
    reply = s.recv(1024) # 1024 is max data that can be received
    print ("Received " + repr(reply))
s.close()

Upvotes: 0

Related Questions