利用Python编写UDP客户端

  本代码主要运用到的模块,并且利用面向对象思想编程:

    1. Socket,实现与服务器端的通讯

    2. Json, 用Json模块封装传输数据,实现可靠传输

    3. Optparse, 实现参数的提取


import socket
import json
import sys
import optparse

class UDPClient:
    def __init__(self, target, port):
     """
      target: UDP服务器的IP地址
      port: UDP服务器的端口
self.target
= target self.port = port self.client_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #实例化一个UDP socket客户端 print("Connecting to UDP server: %s %d" % (self.target, self.port)) self.client_s.connect((self.target, self.port))                       def reliable_send(self, data): json_data = json.dumps(data) self.client_s.sendto(json_data.encode('utf-8'), (self.target, self.port)) def reliable_recv(self): received_data = "" while True: try: received_data = received_data + self.client_s.recvfrom(1024).decode('utf-8') return json.loads(received_data) except ValueError: continue def run(self): while True: command = input("$~ ") self.reliable_send(command) if command == 'q': break print(self.reliable_recv()) self.client_s.close() def get_params(): parser = optparse.OptionParser('Usage: <Program> -t target -p port') parser.add_option('-t', '--target', dest='target', type="string", help="Specify IP address of target") parser.add_option('-p','--port', dest='port', type='int', help='Specify port') options, args = parser.parse_args() if options.target is None or options.port is None: print(parser.usage) sys.exit(0) return options.target, options.port def banner(): banner = """ ****************************************************************** ****************************************************************** UDP Client by Jason Wong V1.0 ****************************************************************** ****************************************************************** """ print(banner) if __name__ == "__main__": banner() target, port = get_params() udpclient = UDPClient(target, port) udpclient.run()

 




 

posted @ 2022-05-01 11:50  Jason_huawen  阅读(494)  评论(0编辑  收藏  举报