我一直在查看我在网上找到的一个小型聊天程序的一些代码。它最初是为 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()
当我使用两个单独的终端运行它们时,它们可以工作,但不发送字符串。
谢谢
请您参考如下方法:
当您使用套接字时,您传递的消息应该以字节为单位,b'bytes'。在 Python 2.x 中,一个 str实际上是一个bytes在 Python 3.x 中
所以你的信息应该是这样的:
message = b'Message I want to pass'
在这里查看 http://docs.python.org/3.3/library/stdtypes.html获取更多信息。
根据 http://docs.python.org/3/library/functions.html#input input 返回一个 str,这意味着您必须将 message 编码为 bytes,如下所示:
message = message.encode()
通过检查 message 的类型来验证这是将 str 转换为 bytes 的正确方法。
