我的套接字程序挂起在clientsocket,address)= serversocket.accept()并且没有吐出错误或其他任何内容。
我按照https://docs.python.org/3/howto/sockets.html
上的说明进行操作我一直试图弄清楚它一个小时,但无济于事。我使用的是python3顺便说一句。我究竟做错了什么?编辑:我的意图全部搞砸了,因为我粘贴错了,但除此之外,我的代码就像我的文件一样。
#import socket module
import socket
#creates an inet streaming socket.
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket created')
#binds socket to a public host, and a well known port
serversocket.bind(('127.0.0.1', 1024))
#print(socket.gethostname())# on desktop prints 'myname-PC')
#become a server socket
serversocket.listen(5) # listens for up to 5 requests
while True:
#accept connections from outside
#print('In while true loop') This works, but we never get to the next print statement. Why the hell is it catching at line 20?
(clientsocket, address) = serversocket.accept()
#clientsocket = serversocket.accept()
print('Ready to serve')
#now we do something with client socket...
try:
message = clientsocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#send an http header line
clientsocket.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
for i in range(0, len(outputdata)):
clientsocket.send(outputdata[i])
clientsocket.close()
except IOERROR:
clientsocket.send('HTTP/1.1 404 File not found!')
clientsocket.close()
答案 0 :(得分:0)
如果你还没有编写客户端脚本/程序来连接套接字并发送数据,那么由于没有什么可以接受的,它也会挂在serversocket.accept()上。但假设你有......
while True:
#accept connections from outside
#print('In while true loop') This works, but we never get to the next print statement. Why the hell is it catching at line 20?
(clientsocket, address) = serversocket.accept()
#clientsocket = serversocket.accept()
它挂起,因为循环永不退出,因为True始终为True。在提供的示例中,一旦接受连接,他们就假装服务器是线程化的,并且想法是创建一个单独的线程来开始读取和处理接收到的数据,从而允许套接字继续监听更多连接。
while True:
# accept connections from outside
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a threaded server
ct = client_thread(clientsocket)
ct.run()