This paper illustrates the data transmission UDP implementation method of Python network programming. Share to everyone for your reference. The specific analysis is as follows:
First, the question:
Do you think that tools like msn,qq on the Web transmit data mysteriously between machines? You want to play a little bit, too? Do you pass data between the two machines? Today let Python tell us the basic principles, of course, just to do simple understanding, the actual situation is much more complicated.
We use Python today to implement a simple UDP program.
Second, the realization of the program:
1) using the module
Sockets Socket module: A socket module is a very simple object-based interface that provides access to low-level BSD socket style networks. Use this module to implement client and server sockets.
A socket is an object that provides the current portable standard for a network application provider on a specific network protocol (for example, TCP/IP,ICMP/IP,UDP/IP, etc.). They allow programs to accept and connect, such as sending and receiving data. In order to establish a communication channel, it is extremely important for each endpoint of a network communication to have a socket object.
2) Establish the server
1th step: Create a Socket object
s = Socket.socket (Family,type)
The value of family can be Af_unix (UNIX domain, interprocess communication on the same machine), or af_inet (TCP or UDP for IP protocol)
The value of the type parameter can be either sock_stream (stream socket) or SOCK_DGRAM (data packet socket), SOCK_RAW (RAW socket).
We use UDP data packet sockets here;
s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)
The 2nd step: Bind the socket to the specified address: S.bind (addressing), addresses must be a two-element group, (Host,port)
We're tying this up. 8081 Port: S.bind (("", Port)
Step 3rd: Call the Recvfrom method to receive data from the client, and the Recvfrom method needs to specify the maximum amount of data that can be received. The data content and the client address will be returned;
?
1 2 3 4 5 6 7 8 |
Import Socket port = 8081 s = socket.socket (socket.af_inet, socket. SOCK_DGRAM) S.bind ((", port)" print "Waiting on port:", port while true:data, addr = S.recvfrom (1024) print "Received:", Data, "from", addr |
3 Client-side establishment
The establishment of the client is very simple, only with the creation of socket objects, specify the port, call the SendTo method to transfer data is OK, as follows;
?
1 2 3 4 5 |
Import Socket port = 8081 host = "localhost" s = socket.socket (socket.af_inet, socket. SOCK_DGRAM) s.sendto ("hello! It ' s working. ", (host, Port)) |
Using datagrams to send short text messages is very simple, if you want reliable data transmission, this method is not good, if the server is not available, the information will be lost, the next section will learn how to use the TCP protocol to transfer information.
I hope this article will help you with your Python programming.