簡體   English   中英

Python套接字腳本。 我究竟做錯了什么?

[英]Python Socket Scripting. What am i doing wrong?

我的套接字程序掛在clientsocket(地址)= serversocket.accept()上,不會吐出任何錯誤或其他信息。

我按照https://docs.python.org/3/howto/sockets.html上的說明進行操作

我一直在試圖弄清楚一個小時,但無濟於事。 我正在使用python3 btw。 我究竟做錯了什么? 編輯:我的想法都搞砸了,因為我粘貼錯了,但除此之外,我的代碼是我在文件中擁有的。

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

如果您尚未編寫客戶端腳本/程序來連接到套接字並發送數據,則由於沒有任何內容可以接受,因此它也將掛在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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM