Introduction to socket
1. How to communicate between processes on different computers
The first problem to be solved is how to uniquely identify a process, otherwise communication can not be started!
On a computer, a process can be uniquely identified by a process number (PID), but this is not feasible in the network.
In fact, the TCP/IP protocol family has helped us solve this problem. The "ip address" of the network layer can uniquely identify the host in the network, while the "protocol + port" of the transport layer can uniquely identify the application process (process) of the host.
In this way, the ip address, protocol and port can be used to identify the process of the network, and the process communication in the network can use this mark to interact with other processes.
Note: The so-called process refers to: the running program and the resources used at run time are called process as a whole.
Inter-process communication refers to the sharing of data between running programs, which will be discussed in detail later in the course. Don't worry about knowledge such as network layer.
2. What is socket?
Socket (socket for short) is a way of interprocess communication. One of the main differences between socket and other interprocess communication is:
It can realize inter-process communication between different hosts. Most of the various services on our network are based on Socket to complete communication.
For example, we browse web pages, QQ chat, email and so on every day.
3. Create socket
Using socket module function socket in Python can accomplish:
import socket socket.socket(AddressFamily, Type)
Explain:
-
The function socket.socket creates a socket with two parameters:
-
Address Family: You can choose AF_INET (for Internet inter-process communication) or
-
AF_UNIX (for communication between processes on the same machine), commonly used in practice AF_INET Type: socket type, can be
SOCK_STREAM (Streaming Socket, Mainly Used for TCP Protocol) or SOCK_DGRAM (Datagram Socket, Mainly Used for UDP Protocol)
Create a UDP socket (udp socket)
import socket
# Create sockets for udp s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Here is the function of using sockets (omitted)... # Close sockets when not in use s.close()
Explain
-
List item
-
The socket usage process is very similar to the file usage process.
-
Create sockets
-
Receiving/sending data using sockets
-
Close
udp network program-sending and receiving data
Communication Template
Creating a network program process based on udp is very simple. The specific steps are as follows:
- Create client socket
- Send/receive data
- Close
send data
#coding=utf-8 from socket import * # 1. Create udp sockets udp_socket = socket(AF_INET, SOCK_DGRAM) # 2. Prepare the address of the recipient # '192.168.1.103'denotes the destination ip address # 8080 represents destination port dest_addr = ('192.168.1.103', 8080) # Note that tuples, ip strings, and ports are numbers # 3. Getting data from keyboard send_data = input("Please enter the data to be sent:") # 4. Send data to a specified program on a specified computer udp_socket.sendto(send_data.encode('utf-8'), dest_addr) # 5. Close sockets udp_socket.close()
receive data
#coding=utf-8 from socket import * # 1. Create udp sockets udp_socket = socket(AF_INET, SOCK_DGRAM) # 2. Prepare the address of the recipient dest_addr = ('192.168.236.129', 8080) # 3. Getting data from keyboard send_data = input("Please enter the data to be sent:") # 4. Send data to a designated computer udp_socket.sendto(send_data.encode('utf-8'), dest_addr) # 5. Waiting to receive data sent by the other party recv_data = udp_socket.recvfrom(1024) # 1024 represents the maximum number of bytes received this time # 6. Display the data sent by the other party # Received data recv_data is a tuple # The first element is the data sent by the other party. # The second element is the ip and port of the other party. print(recv_data[0].decode('gbk')) print(recv_data[1]) # 7. Close sockets udp_socket.close()
Coding Conversion
STR - > bytes: encode coding
Bytes - > str: decode decoding
>>> text = 'I am the text' >>> text 'I am the text' >>> print(text) //I am the text >>> bytesText = text.encode() >>> bytesText b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac' >>> print(bytesText) b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac' >>> type(text) <class 'str'> >>> type(bytesText) <class 'bytes'> >>> textDecode = bytesText.decode() >>> textDecode 'I am the text' >>> print(textDecode) //I am the text
The decode() and encode() methods can accept parameters, which are declared as follows:
bytes.decode(encoding="utf-8", errors="strict") str.encode(encoding="utf-8", errors="strict")
Note: The default Chinese encoding in windows is GBK, so the parameters of "gbk" encoding should be passed in when sending data.
udp binding information
Every time a network program is re-run, if it is not determined which port to use, the system will allocate randomly by default.
Keep in mind that this network program uniquely identifies the program on the port during operation, so if the network program on other computers wants to send data to this program, it needs to send this number (port).
Generally speaking, there are many network programs running on a computer. In order not to occupy the same port number with other network programs, udp port number is usually not bound in programming.
But if you need to make a server-side program, you need to bind it.
#coding=utf-8 from socket import * # 1. Create sockets udp_socket = socket(AF_INET, SOCK_DGRAM) # 2. Bind local information. If a network program is not bound, the system will be allocated randomly. local_addr = ('', 7788) # ip address and port number, ip generally do not need to write, indicating any ip of this machine udp_socket.bind(local_addr) # 3. Waiting to receive data sent by the other party recv_data = udp_socket.recvfrom(1024) # 1024 represents the maximum number of bytes received this time # 4. Display received data print(recv_data[0].decode('gbk')) # 5. Close sockets udp_socket.close()
summary
- A udp network program can be unbound. At this time, the operating system will randomly allocate a port. If the program port is re-run, it may change.
- 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 or not.
udp chatter
import socket def send_msg(udp_socket): """Get keyboard data and send it to each other""" # 1. Input data from keyboard msg = input("\n Please enter the data to be sent:") # 2. Enter the ip address of the other party dest_ip = input("\n Please enter each other's ip address:") # 3. Enter each other's port dest_port = int(input("\n Please enter each other's port:")) # 4. Send data udp_socket.sendto(msg.encode("utf-8"), (dest_ip, dest_port)) def recv_msg(udp_socket): """Receive data and display""" # 1. Receiving data recv_msg = udp_socket.recvfrom(1024) # 2. Decoding recv_ip = recv_msg[1] recv_msg = recv_msg[0].decode("utf-8") # 3. Display the received data print(">>>%s:%s" % (str(recv_ip), recv_msg)) def main(): # 1. Create sockets udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2. Binding local information udp_socket.bind(("", 7890)) while True: # 3. Selection function print("="*30) print("1:send message") print("2:receive messages") print("="*30) op_num = input("Please enter the serial number of the function to be operated on.:") # 4. Call the corresponding function according to the choice if op_num == "1": send_msg(udp_socket) elif op_num == "2": recv_msg(udp_socket) else: print("The input is incorrect. Please re-enter it....") if __name__ == "__main__": main()