udp is no link, and then start the service can receive messages directly, no need to establish a link in advance
A, UDP basic use
Server
Import Socket Server = socket.socket (type = socket.SOCK_DGRAM) # the UDP protocol server.bind (( ' 127.0.0.1 " , 8080 )) the while True: Data, addr = server.recvfrom (1024 ) Print ( ' Data: ' , Data) # client message sent by the Print ( ' address: ' , addr) # client to address server.sendto (data.upper (), addr)
Client
Import Socket Client = socket.socket (type = socket.SOCK_DGRAM) the server_address = ( ' 127.0.0.1 ' , 8080 ) the while True: client.sendto (B ' Hello ' , the server_address) Data, addr = client.recvfrom (1024 ) Print ( ' service data sent by the end ' , data) Print ( ' server address sent ' , addr)
Two, UDP achieve simple version of QQ
Server
import socket server = socket.socket(type=socket.SOCK_DGRAM) server.bind(('127.0.0.1',8080)) while True: data,addr = server.recvfrom(1024) print(data.decode('utf-8')) msg = input('>>>:') server.sendto(msg.encode('utf-8'),addr)
Client
import socket client = socket.socket(type=socket.SOCK_DGRAM) server_address = ('127.0.0.1',8080) while True: msg = input('<<<:') msg = '来自客户端1的消息:%s'%msg client.sendto(msg.encode('utf-8'),server_address) data,server_addr = client.recvfrom(1024) print(data.decode('utf-8'))
Third, upload files operations
Server
import socket import os import json import struct server = socket.socket() server.bind(('127.0.0.1',8080)) server.listen(5) while True: conn,addr = server.accept() while True: try: header_len = conn.recv(4) # 解析字典报头 header_len = struct.unpack('i',header_len)[0] #Then receiving data dictionary header_dic = conn.recv (header_len) real_dic = json.loads (header_dic.decode ( ' UTF-. 8 ' )) # acquires data length total_size = real_dic.get ( ' FILE_SIZE ' ) # loop receives and writes the file = recv_size 0 with Open (real_dic.get ( ' file_name ' ), ' WB ' ) AS F: the while recv_size < total_size: Data = conn.recv (1024 ) f.write(data) recv_size += len(data) print('上传成功') except ConnectionResetError as e: print(e) break conn.close()
Client
Import socket Import json Import os Import struct Client = socket.socket () the client.connect (( ' 127.0.0.1 ' , 8080 )) the while True: # get movie listings cycle through MOVIE_DIR = r ' D: \ Python full-time 10 video \ day25 \ video ' movie_list = the os.listdir (MOVIE_DIR) # Print (movie_list) for I, Movie in the enumerate (movie_list,. 1 ): Print (I, Movie) # user selects choice = input (' Please to Upload >>> Choice Movie: ' ) # determines whether the number if choice.isdigit (): # string into digital int Choice = int (Choice) -. 1 # determines whether the user selected within the range not listed if Choice in the Range (0, len (movie_list)): # get the user wants to upload a file path path = movie_list [Choice] # absolute path splicing file file_path = os.path.join (MOVIE_DIR, path) # get file size file_size = os.path.getsize (file_path) # define a dictionary res_d = { ' File_name ' : ' sexy dealer online licensing .mp4 ' , ' FILE_SIZE ' : FILE_SIZE, ' MSG ' : ' attention to the body, nutrition drink Express ' } # serialized dictionary json_d = json.dumps (res_d) json_bytes json_d.encode = ( ' UTF-. 8 ' ) # 1. first make dictionary format header header struct.pack = ( ' I ' , len (json_bytes)) # 2. send dictionary header client.send (header) # 3. recurrent dictionary client.send (json_bytes) # 4. retransmission data file (file open loop transmission) with Open (file_path, ' RB ' ) AS F: for Line in F: Client. Send (Line) the else : Print ( ' Not in Range ' ) the else : Print ( ' MUST BE A Number ' )
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): while True: data = self.request.recv(1024) print(self.client_address) print(data.decode('utf-8')) self.request.send(data.upper()) if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer) # 创建一个基于TCP的对象 server.serve_forever () # start the service object
import socket client = socket.socket() client.connect(('127.0.0.1',8080)) while True: client.send(b'hello') data = client.recv(1024) print(data.decode('utf-8'))