Last active
December 4, 2018 11:32
-
-
Save Koswu/f813aaf201212310733829b27c7db384 to your computer and use it in GitHub Desktop.
Echo 服务端
This file contains 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
#!/usr/bin/env python3 | |
''' | |
An easy TCP ECHO Server | |
Author:KosWu | |
''' | |
import socket | |
from queue import Queue | |
import threading | |
import argparse | |
HOST = '' | |
BUFSIZE = 1024 | |
#socketSet = set() | |
threadSet = set() | |
messageQueue = Queue() | |
isRunning = True | |
#对每一个连接进行处理 | |
def handle(clientSocket, clientAddr): | |
messageQueue.put('connected form: %s:%d'%(clientAddr[0], int(clientAddr[1]))) | |
clientSocket.settimeout(5) | |
while isRunning: | |
try: | |
data = clientSocket.recv(BUFSIZE) | |
except socket.timeout: | |
continue | |
except Exception as err: | |
messageQueue.put(err) | |
break | |
except Exception as err: | |
print(err) if not data: | |
#socketSet.remove(s) | |
break | |
clientSocket.send(data) | |
clientSocket.close() | |
messageQueue.put('%s:%d is disconnected'%(clientAddr[0], clientAddr[1])) | |
threadSet.remove(threading.current_thread()) | |
#消息处理线程 | |
def message_process(): | |
while isRunning: | |
if not messageQueue.empty(): | |
print(messageQueue.get()) | |
def main(): | |
#解析参数,获取监听端口 | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-p', '--port' , help='listening port of the server', type = int, default = 10007) | |
args = parser.parse_args() | |
port = args.port | |
if port not in range(1, 65535): | |
raise Exception("Port is out of range.") | |
addr = (HOST, args.port) | |
#使用ipv4,和TCP连接 | |
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
tcpSocket.bind(addr) | |
#设置最大连接数 | |
tcpSocket.listen(5) | |
messageQueue.put('Listening on port %d, Waiting for connection..'%int(args.port)) | |
logger_thread = threading.Thread(target = message_process, daemon = True) | |
logger_thread.start() | |
try: | |
while True: | |
clientSocket, clientAddr = tcpSocket.accept() | |
t = threading.Thread(target = handle, args=(clientSocket, clientAddr), daemon = True) | |
threadSet.add(t) | |
t.start() | |
except KeyboardInterrupt: | |
isRunning = False | |
tcpSocket.close() | |
print ("Echo Server is shutting down") | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment