#Python 網路程式設計-TCP服務端基礎篇(一)簡單的傳送和接收
##TCP服務端基本流程圖
TCP服務端-單個客戶端
1 import socket 2 _BUFFSIZE = 1024 3 ip_addr = r"10.110.36.27" 4 port = 9000 5 ip_port = (ip_addr,port) 6 socket_server = socket.socket() 7 socket_server.bind(ip_port) 8 socket_server.listen() 9 print("正在等待客戶端連線") 10 conn,addr = socket_server.accept() 11 print("當前連線的ip",addr) 12 while 1: 13 print("正在等待接收資訊") 14 receive_msg = conn.recv(_BUFFSIZE) 15 print("接收到的資訊為",receive_msg.decode()) 16 if 'quit' in receive_msg.decode(): 17 break 18 # send_msg = input("請輸入要傳送的資訊") 19 conn.sendall(receive_msg) 20 socket_server.close()
TCP服務端-多個客戶端(二)
1 import socket 2 import threading 3 import time 4 import re 5 _BUFFSIZE = 1024 6 _MAX_CLIENT = 5 7 ip_addr = r"10.110.36.27" 8 port = 9000 9 ip_port = (ip_addr,port) 10 # socket_server = socket.socket() 11 # socket_server.bind(ip_port) 12 # socket_server.listen(_MAX_CLIENT) 13 # print("正在等待客戶端連線") 14 15 # conn,addr = socket_server.accept() 16 # print("當前連線的ip",addr) 17 18 19 class TcpServer(object): 20 def __init__(self,ip,port): 21 self._ip = ip 22 self._port = port 23 24 25 def serve_start(self): 26 self.serve = socket.socket() 27 self.serve.bind((self._ip,self._port)) 28 self.serve.listen(_MAX_CLIENT) 29 30 31 def serve_stop(self): 32 self.serve.close() 33 34 35 # def serve_wait(self): 36 # self._con,self._addr = self.serve.accept() 37 38 def con_info(self): 39 while 1: 40 print("正在等待客戶端連線") 41 self.con,self.addr = self.serve.accept() 42 print('當前連線ip',self.addr) 43 self.client_listen(self.con,self.addr) 44 45 def receive_send(self,conn,addr): 46 # # while 1: 47 # conn,addr = self.serve.accept() 48 # print("當前連線:",addr) 49 # # print("%s d",addr) 50 while 1: 51 # print("來自%s的資訊為%s"%(addr,receive_msg)) 52 receive_msg = conn.recv(_BUFFSIZE) 53 print("來自%s的資訊為%s"%(addr,receive_msg)) 54 if receive_msg.decode() =='': 55 break 56 else: 57 if 'quit' in receive_msg.decode(): 58 # conn.close() 59 break 60 # send_msg = input("請輸入要傳送的資訊") 61 conn.sendall(receive_msg) 62 print("關閉連線:",addr) 63 conn.close() 64 65 def client_listen(self,conn,addr): 66 thread_1 = threading.Thread(target=self.receive_send,args=(conn,addr,)) 67 thread_1.start() 68 69 try: 70 server_obj = TcpServer(ip_addr,port) 71 server_obj.serve_start() 72 server_obj.con_info() 73 # server_obj.client_listen() 74 finally: 75 server_obj.serve_stop()