Network Programming -python achieve -UDP (1.1.2)

@(network programming)

What is 1.UDP

Internet protocol suite supports a connectionless transport protocol, the protocol called User Datagram Protocol (UDP, User Datagram Protocol). UDP provides a method for IP datagrams can be sent without establishing a connection for the application package. RFC 768 [1] describes a UDP.
Internet has two main transport layer protocols, complement each other. No connection is UDP, in addition to its function to send packets to the application and allow them to own protocol architecture at the desired level, there is little special things to do. It is connection-oriented TCP, the protocol to do almost everything

2. code implementation

The sender

import socket

def main():
    #创建一个udp套接字
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    #如果没有绑定,故接收端只有随机端口接收
    udp_socket.bind(("",7789))
    while True:
        #获取数据
        send_data = input("请输入要发送的数据")

        if send_data == "exit":
            break

        #ip,port
        address  = ("127.0.0.1",7788)

        #可以使用套接字收发数据  第一个参数必须为二进制数据 第二个参数是一个元组(ip,port)
        # udp_socket.sendto(b"hahaha",address)
        udp_socket.sendto(send_data.encode("utf-8"),address)



    #关闭
    udp_socket.close()

if __name__ == '__main__':
    #发送服务器启动
    main()

Receiving end

import socket


def main():
    # 创建一个udp套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 绑定本地的相关信息,如果一个网络程序不绑定,系统会随机分配
    address = ("127.0.0.1", 7788)
    udp_socket.bind(address)


    for i in range(0,100):
        #等待接收对方发送的数据 1024表示的是每一次接收的最大字节数
        recv_data = udp_socket.recvfrom(1024)
        recv_mess  = recv_data[0]
        send_addre = recv_data[1]
        print(recv_mess.decode("utf-8"),str(send_addre))#recv_mess.decode("utf-8")
    # 关闭
    udp_socket.close()


if __name__ == '__main__':
    print("接收服务器启动")
    main()

note

  • The receiving end must be bound port and ip address
  • The transmit end can not bind when the host is assigned a random port
  • The sender sends the data to be encoded, the corresponding receiving end to be decoded
  • Then the number of bytes later recvfrom
  • recvfrom returns a list of data tuples waving, wherein the received data is 0, 1 for the sender's address

Guess you like

Origin www.cnblogs.com/simon-idea/p/11314602.html