We have also learned about the UDP protocol. Next we will focus on the creation process of the UDP client. First, let's take a look at how to create a file in a Unix system. So please read the article and read the source code.
Create a UDP client
In the four programs described in this section, the following UDP client code is the shortest. The pseudocode is as follows:
- Cs = socket () # create a client socket
- Comm_loop: # communication Loop
- Cs. sendto ()/cs. recvfrom () # Send/receive DIALOG)
- Cs. close () # close the client socket
After the socket object is created, we enter a dialog loop with the server. After the communication ends, the socket is closed. The actual code of tsUclnt. py is provided in example 16.4.
Line-by-line explanation
1 ~ 3 rows
Like the TCP client, after the Unix startup information line, we imported all the attributes of the socket module.
5 ~ 10 rows
Because our server is also running on the local machine, our client still uses the local machine and the same port number. Naturally, the buffer size is still 1 K. The method for creating a socket is the same as that in the UDP server.
12 ~ 22 rows
The loop of the UDP client is basically the same as that of the TCP client. The only difference is that we do not need to establish a connection with the UDP server first, but directly send the message and wait for the server to reply. After obtaining a string with a timestamp, display it on the screen and continue with other messages. After the input is complete, exit the loop and close the socket.
Example 16.4 UDP timestamp client tsUclnt. py)
When you create a UDP client, the program prompts the user to enter the information to be sent to the server, and displays the result returned by the server with a timestamp.
#!/usr/bin/env python
from socket import *
HOST=' localhost '
PORT=21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
udpCliSock = socket(AF_INET, SOCK_DGRAM)
while True:
data = raw_input('> ')
if not data:
break
udpCliSock.sendto(data, ADDR)
data, ADDR = udpCliSock.recvfrom(BUFSIZ)
if not data:
break
print dataudpClisock.close()
udpCliSock.close()