我一直在寻找一些我在网上找到的小聊天程序的代码。它最初是为2.7编写的,但似乎与3.2一起使用。唯一的问题是我不能发送字符串,只能发送数字:
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(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(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()
当我使用两个单独的终端运行它们时,它们可以工作,但不发送字符串。
谢谢
答案 0 :(得分:2)
当您使用套接字时,您传递的消息应该以字节为单位b'bytes'
。在Python 2.x中,str
实际上是{3.}}在Python 3.x
所以你的信息应该是这样的:
message = b'Message I want to pass'
点击此处bytes
了解详情。
根据http://docs.python.org/3.3/library/stdtypes.html input
返回str
,这意味着您必须将message
编码为bytes
,如下所示:
message = message.encode()
通过检查str
的类型,确认这是将bytes
转换为message
的正确方法。
答案 1 :(得分:0)
您的套接字代码是正确的,由于raw_input
与input
导致的无关错误,它只是失败了。您可能打算从shell中读取一个字符串,而不是读取一个字符串并尝试将其评估为input
所做的Python代码。
请改为尝试:
<强> 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()