Python套接字脚本。我做错什么了?

2024-10-06 20:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的套接字程序挂起在clientsocket,address)=服务器套接字。接受()也不会说我们有错什么的。你知道吗

我遵循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()

Tags: toimportansendforaddresshtmlsocket
1条回答
网友
1楼 · 发布于 2024-10-06 20:29:29

如果您还没有编写客户端脚本/程序来连接到套接字并向其发送数据,那么它也会挂起服务器套接字。接受()因为没有什么可接受的。但假设你有。。。你知道吗

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()

相关问题 更多 >