Network programming - python implementation - socket (1.1.2)


@ (Network programming)

What is 1.UDP?

Internet Protocol Set supports a connectionless transport protocol, which is called User Datagram Protocol (UDP). UDP provides a way for applications to send encapsulated IP datagrams without establishing connections. RFC 768 [1] describes UDP.
The transport layer of the Internet has two main protocols that complement each other. Connectionless is UDP, which does not do anything special except to send data packets to applications and allow them to structure their own protocols at the required level. Connection-oriented is TCP, which does almost everything.

2. Code Implementation

Sending end

import socket

def main():
    #Create a udp socket
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    #If there are no bindings, the receiver has only random ports to receive
    while True:
        #get data
        send_data = input("Please enter the data to be sent")

        if send_data == "exit":

        address  = ("",7788)

        #The first parameter to send and receive data using sockets must be binary data. The second parameter is a tuple (ip,port).
        # udp_socket.sendto(b"hahaha",address)


if __name__ == '__main__':
    #Sender Server Start

receiving end

import socket

def main():
    # Create a udp socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # Bind local information. If a network program is not bound, the system will be allocated randomly.
    address = ("", 7788)

    for i in range(0,100):
        #The data 1024 waiting to be sent by the receiving party represents the maximum number of bytes received at a time.
        recv_data = udp_socket.recvfrom(1024)
        recv_mess  = recv_data[0]
        send_addre = recv_data[1]
    # Close

if __name__ == '__main__':
    print("Receiving Server Start")

Be careful

  • Receiver must bind port and ip address
  • The sender can be unbound, at which point the host allocates a random port
  • The data sent from the sending end must be encoded, and the corresponding receiver must decode it.
  • recvfrom is followed by the number of bytes
  • The data returned by recvfrom is a list of waving tuples, of which 0 is the received data and 1 is the sender's address.

Tags: PHP socket network Programming

Posted on Mon, 07 Oct 2019 14:03:19 -0700 by uptime