寫過Socket網絡編程的代碼,大體都知道一個tcp服務器的主要步驟:socket-->bind-->listen-->accept-->recv/send-->close, tcp客戶端的主要 步驟:socket-->connect-->recv/send-->close。有上述的瞭解的話,會以爲Python中的socket編程也是相似的。python
以一個echo服務爲例子,進行說明:
編程
1)首先是服務端的代碼:
服務器
# This is a echo server. import socket import sys try: #1. create socket serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print("socket failed") sys.exit(-1) print("socket success") # serv_addr = ('127.0.0.1', 8080) host = '' port = 8000 #2. bind to 8000 port and listen serv_sock.bind((host, port)) serv_sock.listen(5) while True: #3. accept connection from client client_sock, client_addr = serv_sock.accept() print("connected by ", client_addr) while True: buf = client_sock.recv(10240) if not buf: print("Exit", client_addr) client_sock.close() break else: print("recv from client: ", buf) client_sock.send(buf)
2)echo客戶端代碼:
網絡
# This is a echo client. import socket import sys try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print('socket failed!') sys.exit(-1) print("socket success") # serv_addr = ('127.0.0.1', 8080) host = '127.0.0.1' port = 8000 try: sock.connect((host, port)) except socket.error: print("connect %s failed" % host) sys.exit(-1) while True: try: #message = "hello" message = input(">>") if not message: break else: sock.sendall(message.encode('utf8')) reply = sock.recv(10240) print('reply: %s' % reply.decode('utf8')) except EOFError: print("EOF\n") break print("Exit...") #sock.shutdown(socket.SHUT_RDWR) sock.close()
上述就是一個簡單的echo服務,簡單的展現了socket模塊中的套接字編程的相關方法。
多線程
在實際的網絡開發中,主要的模型有:多進程,多線程,事件驅動select/epoll,異步非阻塞。這些會在後面的文章中分別進行說明。
異步