Created
May 11, 2016 13:33
-
-
Save limboinf/50cbac9994caa44bb8587c642dd7c0f7 to your computer and use it in GitHub Desktop.
在套接字服务器中使用ThreadingMinIn类
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
""" | |
在套接字服务器中使用ThreadingMinIn类 | |
:copyright: (c) 2016 by fangpeng(@beginman.cn). | |
:license: MIT, see LICENSE for more details. | |
""" | |
import os | |
import socket | |
import threading | |
import SocketServer | |
SERVER_HOST = 'localhost' | |
SERVER_PORT = 0 # 内核会动态选择端口 | |
BUF_SIZE = 1024 | |
ECHO_MSG = "Hello echo serever!" | |
class ThreadTCPServer(SocketServer.ThreadingMixIn, | |
SocketServer.TCPServer): | |
"""Nothing to add here, inherited everything necessary from parents""" | |
pass | |
class ThreadServerRequestHandler(SocketServer.BaseRequestHandler): | |
def handle(self): | |
data = self.request.recv(BUF_SIZE) | |
current_thread = threading.current_thread() | |
response = "%s: %s" % (current_thread.name, data) | |
print "Server send:%s" % response | |
self.request.sendall(response) | |
def client(ip, port, msg): | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.connect((ip, port)) | |
try: | |
sock.sendall(msg) | |
response = sock.recv(BUF_SIZE) | |
print "Client received: %s" % response | |
finally: | |
sock.close() | |
def main(): | |
# Launch the server | |
server = ThreadTCPServer((SERVER_HOST, SERVER_PORT), ThreadServerRequestHandler) | |
ip, port = server.server_address | |
# 创建守护线程并启动服务 | |
server_thread = threading.Thread(target=server.serve_forever) # serve_forever 一次处理一个请求,直到关闭 | |
server_thread.setDaemon(True) # don't hang on exit | |
server_thread.start() | |
print "Server loop running PID:%s" % os.getpid() | |
# Launch the client | |
client(ip, port, "hello 1") | |
client(ip, port, "hello 2") | |
client(ip, port, "hello 3") | |
# Clean | |
server.shutdown() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment