Cookbook: Recipe 13.1. Passing Messages with Socket into rams
I recently spent some time learning network-related knowledge. Today I will learn how to use python to transmit data on two machines.
Do you think it is mysterious that tools like msn and qq on the Internet transmit data between multiple machines? Do you want to transfer data between two machines? Today, let python tell us the basic principles. Of course, it's just a simple understanding, but the actual situation is much more complicated.
Today, we use python to implement a simple udp program.
1) modules used
(Socket) socket module: the socket module is a very simple object-based interface that provides access to the low-layer BSD socket style network. This module can be used to implement client and server sockets.
A socket is a network application provider that provides portable standard objects for a specific network protocol (such as TCP/IP, ICMP/IP, UDP/IP. They allow programs to accept and connect, such as sending and receiving data. To establish a communication channel, each endpoint of network communication has a socket object.
2) create a server
Step 2: Create a socket object
S = socket. socket (family, type)
The value of family can be AF_UNIX (unix domain used for communication between processes on the same machine) or AF_INET (corresponding to TCP or UDP of IP protocol)
The value of the Type parameter can be: SOCK_STREAM (stream socket), SOCK_DGRAM (Data PACKET socket), and SOCK_RAW (raw socket ).
We use udp data PACKET socket here;
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
Step 2: bind the socket to the specified address: s. bind (address). The address must be a dual-element group (host, port)
We bind port 8081 of the local machine here: s. bind ("", port ))
Step 2: Call the recvfrom method to receive data from the client. The recvfrom method must specify the maximum data size that can be received. The data content and client address will be returned;
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) create a client
It's easy to create a client. just create a socket object, specify the port, and call the sendto method to transfer data;
Import socket
Port = 8081
Host = "localhost"
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
S. sendto ("Hello! It's working. ", (host, port ))
It is very easy to send short text information using datagram. If you want to transmit data reliably, this method is not feasible. If the server is unavailable, the information will be lost, the next section describes how to use the tcp protocol to transmit information.
Vivilisa write in 03.17.2009