udp programming for python network-Socket (24)

Introduction to udp

  • udp - User Datagram Protocol is a simple connectionless datagram-oriented transport layer protocol.
  • udp does not provide reliability; it simply sends datagrams from applications to the IP layer, but it does not guarantee that they will reach their destinations.
  • udp does not need to establish a connection between client and server before transmitting datagrams, and there is no mechanism such as timeout resend, so the transmission is fast.
  • udp is a connectionless-oriented protocol in which each datagram is an independent piece of information, including a complete source or destination address, which travels to the destination by any possible route on the network. Therefore, whether or not the destination can be reached, when the destination can be reached, and the correctness of the content cannot be guaranteed.

 

2. udp features:

udp is a connectionless communication protocol. udp data includes destination port number and source port number information. Because communication does not require a connection, broadcast transmission can be achieved.udp has size limitations when transferring data, each transmitted datagram must be limited to 64KB.udp is an unreliable protocol, and the datagrams sent by the sender do not necessarily reach the receiver in the same order.udp is a message-oriented protocol. There is no need to establish a connection when communicating. Naturally, data transmission is unreliable. udp is generally used for multipoint communication and real-time data business, such as:

  • Voice broadcasting
  • TFTP (Simple File Transfer)
  • SNMP (Simple Network Management Protocol)
  • RIP (Routing Information Protocol, e.g. Reporting Stock Market, Aviation Information)
  • DNS (Domain Name Interpretation)

 

3. udp network program - sending data

The process of creating a udp client program is simple, with the following steps:

  1. Create Client Socket
  2. Send/Receive Data
  3. Close

The code is as follows:

#coding=utf-8
from socket import *

#1,Establish socket socket
#socket(Parameter 1, parameter 2)
#Parameter 1 = AF_INET Changeless
#Parameter 2 = SOCK_DGRAM Express udp,As mentioned in the previous article SOCK_STREM Express tcp
udpSocket = socket(AF_INET,SOCK_DGRAM)

#2,Prepare the recipient's address
sendAddress = ("192.168.100.101",8080)

#3,Enter the data you need to send from the keyboard
sendData = input("Enter the data you want to send:")

#4,Send data to specified computer
udpSocket.sendto(sendData.encode(),sendAddress)

#5,Close socket socket
udpSocket.close()

Run the program:

At this time, I sent a message to another program with IP address 192.168.100.101 and port number 8080,'I'm Hogo'.With the help of network debugging assistant software for testing, network debugging assistant has systems on each platform, you can download and use them yourself.

Description: My code runs on a windows computer, my network debugging assistant runs on a Mac computer, or you can use a virtual machine to test if you don't have two computers.

 

4. udp network program - receiving data

#coding=utf-8
from socket import *

#1,Establish socket socket
udpSocket = socket(AF_INET,SOCK_DGRAM)

#2,Prepare the recipient's address
sendAddress = ("192.168.100.101",8080)

#3,Enter the data you need to send from the keyboard
sendData = input("Enter the data you want to send:")

#4,Send data to specified computer
udpSocket.sendto(sendData.encode(),sendAddress)

#5,Waiting to receive data from the other party
receiveData = udpSocket.recvfrom(1024)

#6,Display data sent by the other party
print(receiveData)

#7,Close socket socket
udpSocket.close()

Run the program:

 

5. udp network program-port problem

Variable port number: Rerun the script several times, and then in the Network Debugging Assistant, see the following:

Explain:

  • The difference between the numbers in the red circle in the figure above is that this number identifies the network program. When it is run again, if you are not sure which one to use, the system will be assigned randomly by default.
  • Keep in mind that this network program uniquely identifies this program when it is running, so if a network program on another computer wants to send data to this program, it needs to send the program identified by this number (i.e., port).

 

6. udp binding information

In general, there are many network programs running on your computer in one day, but the port numbers you use are not known in many cases. In order not to occupy the same port number with other network programs, udp's port number is usually not bound in programming, but if you need to make a server-side program, it needs to be bound.Just like the alarm phone is changing every day, the world is bound to be chaotic, so general service programs often need a fixed port number, which is called port binding.

Binding example

#coding=utf-8
from socket import *

#1,Establish socket socket
udpSocket = socket(AF_INET,SOCK_DGRAM)

#2,Binding information, if a network program is not bound, the system will be randomly assigned
bindAddress = ("",7781)#ip Address and port number, ip Normally not written, any one of this machine ip
udpSocket.bind(bindAddress)

#3,Waiting for Receiver to Send Message
receiveData = udpSocket.recvfrom(1024)

#4,Display data sent by the other party
print(receiveData)

#5,Close socket socket
udpSocket.close()

windows PC Send Information

The mac computer receives the following information:

Explain:

  • A udp network program that can be unbound, in which case the operating system will randomly assign a port, which may change if the secondary program port is rerun
  • A udp network program can also bind information (ip address, port number). If the binding is successful, the operating system uses this port number to distinguish whether the received network data is the process?

 

7. udp network communication process

 

8. udp application: multi-threaded chat room

#coding=utf-8
from threading import Thread
from socket import *

#receive data
def receiveInfo():
    while True:
        receiveData = udpSocket.recvfrom(1024)
        print("<<%s:%s"%(str(receiveData[1]),str(receiveData[0])))

#send data
def sendInfo():
    while True:
        sendData = input("")
        udpSocket.sendto(sendData.encode("gb2312"),(destIp,destPort))

udpSocket = None
destIp = ""
destPort = 0

def main():
    global udpSocket
    global destIp
    global destPort

    destIp = input("Opposite party's IP:")
    destPort = int(input("Opposite party's Port:"))

    udpSocket = socket(AF_INET,SOCK_DGRAM)
    udpSocket.bind(("",4567))#The reason for writing two () here is that the"",4567)Use as a whole tuple

    tr = Thread(target = receiveInfo)
    ts = Thread(target = sendInfo)

    tr.start()
    ts.start()

    tr.join()
    ts.join()

if __name__ == '__main__':
    main()

On a Mac computer, the following program is executed:

Run the Network Debugging Assistant on a windows computer as follows:

This is multiprogram communication with udp of socket first.

Keywords: Python socket network Windows Mac

Added by Pobega on Sun, 19 May 2019 07:53:51 +0300