Python教程

利用Python编写UDP客户端

本文主要是介绍利用Python编写UDP客户端,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

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

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

    3. Optparse, 实现参数的提取



import socket
import json
import sys
import optparse

class UDPClient:
    def __init__(self, target, port):
        self.target = target
        self.port = port
        self.client_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        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()

 



 

这篇关于利用Python编写UDP客户端的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!