【发布时间】:2015-06-21 14:19:04
【问题描述】:
我的客户端每次尝试连接到我的 python 套接字服务器时都会崩溃。我不知道为什么,但是我的服务器接缝可以正常启动,然后当我启动客户端时,它会建立与服务器的连接,但直接崩溃。我所做的几乎和他们在py socket docs 中所说的一样,所以我想知道我是否错过了一些东西,或者只是盲目地盯着一些简单的东西。任何人都可以帮助我使用python3.4。
server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
print("Recieved: "+(databytes.decode('utf-8')))
response = input("Reply: ")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
data = s.recv(1024)
print("Recieved: "+(data.decode('utf-8')))
response = input("Reply: ")
if response == "exit":
break
s.sendall(response.encode('utf-8'))
s.close()
【问题讨论】:
-
当客户端崩溃时你得到什么输出?
-
服务器说它从 获得了一个连接,客户端在 python shell 中的命令提示符中什么也没说,它说 Traceback(最近一次调用最后一次):文件“C :\Python34\client.py",第 9 行,在
initialMessage = raw_input("Send: ") NameError: name 'raw_input' is not defined -
请看我的回答。
标签: python sockets python-3.x serversocket