[英]How to TCP server serves forever?
大家好!
我是python網絡編程的新手。
我的開發環境如下。
我正在學習“ Python網絡編程食譜”。 本書中有ThreadingMixIn套接字服務器應用程序的示例。
本書的代碼是用Python 2.7編寫的。 因此,我為python 3.4進行了修改。 代碼是...
# coding: utf-8
import socket
import threading
import socketserver
SERVER_HOST = 'localhost'
SERVER_PORT = 0 # tells the kernel to pick up a port dynamically
BUF_SIZE = 1024
def client(ip, port, message):
""" A client to test threading mixin server"""
# Connect to the server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
message = bytes(message, encoding="utf-8")
sock.sendall(message)
response = sock.recv(BUF_SIZE)
print("Client received: {0}".format(response))
finally:
sock.close()
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
""" An example of threaded TCP request handler """
def handle(self):
data = self.request.recv(1024)
current_thread = threading.current_thread()
response = "{0}: {0}".format(current_thread.name, data)
response = bytes(response, encoding="utf-8")
self.request.sendall(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
"""Nothing to add here, inherited everything necessary from parents"""
pass
if __name__ == "__main__":
# Run server
server = ThreadedTCPServer((SERVER_HOST, SERVER_PORT),
ThreadedTCPRequestHandler)
ip, port = server.server_address # retrieve ip address
# Start a thread with the server -- one thread per request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread exits
server_thread.daemon = True
server_thread.start()
print("Server loop running on thread: {0}".format(server_thread))
# Run clients
client(ip, port, "Hello from client 1")
client(ip, port, "Hello from client 2")
client(ip, port, "Hello from client 3")
這段代碼非常完美。 每個客戶端的請求都由新線程處理。 當客戶的請求結束時,程序結束。
我想讓服務器永遠服務。 因此,當其他客戶端的請求到達時,服務器將其響應發送到該客戶端。
我該怎么辦?
感謝您閱讀我的問題。
PS:哦,再說一遍。 我總是在我的堆棧溢出帖子中打個招呼。 在預覽中,它正常顯示。 但是,帖子保存后,第一行總是消失了。 請任何人幫我XD
您的程序退出,因為您的服務器線程是守護程序:
# Exit the server thread when the main thread exits
server_thread.daemon = True
您可以刪除該行,也可以在代碼底部添加server_thread.join()
以防止主線程提早退出。
您將必須在無限循環上運行,並在每個循環上等待來自客戶端的某些數據。 這樣,連接將保持活動狀態。
相同的無限循環使服務器可以接受更多客戶端。
但是,您將必須以某種方式檢測客戶端何時關閉與服務器的連接,因為在大多數情況下不會通知服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.