1.Socket concept
Also called a socket. Used to describe IP addresses and ports, it is a handle to a communication chain. Applications usually make requests to the network or respond to network requests through "sockets". To put it bluntly, it is an interface.
2. Usage
first: instantiate object, constructor:
obj = socket(family, type, proto, fileno, fileno)
family: address family, indicating the protocol used, that is, the protocol of TCP/IPv4
type: Indicates TCP or UDP
protocol : protocol number, the default is 0, generally do not fill in
fileno: if fileno is specified, other parameters will be ignored
second: to bind:
socket.bind(address)
address : IP address and port, here is a tuple
third: start listening:
socket.listen()
In the previous version of listen, parameter n should be added. The parameter n indicates that there can be n links waiting to communicate with the server at the same time. Generally, it is not required.
fourth: call socket function to wait for connection
connection,address = socket.accept()
When the accept method is called, the socket enters the 'waiting' (or blocking) state. When a client requests a connection, the method establishes the connection and returns to the server. The accept method returns a tuple with two elements in the form (connection, address). The first element (connection) is the new socket object through which the server communicates with the client; the second element (address) is the client's internet address.
fifth: processing data
Server and client transfer data through send and recv methods.
The server calls send to send information to the client in the form of a string, and the send method returns the number of characters sent.
The server uses the recv method to receive information from the client.
When calling recv, you must specify an integer to control the maximum amount of data accepted by this call. The recv method will enter the 'blocket' state when receiving data, and finally return a string, which is used to represent the received data. If more than recv allows, the data will be truncated. Excess data will be buffered at the receiver. When recv is called later, the excess data is removed from the buffer.
sixth: close the socket
Usage case:
Socket based on the TCP protocol (TCP is based on the link, the server must be started first, and the client must be connected to the client from the start)
server side:
import socket soc = socket.socket() # create a soc object soc.bind(('127.0.0.1',9789)) # bind the address to the socket soc.listen() # listen port conn,addr = soc.accept() # Receive client port link re = conn.recv(1024) # Receive client information print(re.decode('utf-8')) # To receive the information sent by the client, it must be converted into unicode conn.send('One Piece'.encode('utf-8')) # Send information to the client, it must be bytes type conn.close() soc.close()
client side:
import socket me = socket.socket() # instantiate the object me.connect(('127.0.0.1',9789)) # bind the address to the socket me.send('one piece'.encode('utf-8')) # Send a message to the server ret = me.recv(1024) # Set fixed receive bytes to prevent one load from occupying too much memory print(ret.decode('utf-8')) # Decode the information sent by the server me.close() # close the port
Error-prone point: when the client and server send messages, they must pay attention to the order of receiving and sending
Computer loopback address:
127.0.0.1 , the default is the local address, generally used for testing on your own computer, it does not need to be queried by the switch
Scope of application of tcp protocol:
Suitable for uploading and downloading files, and sending important files, etc. Each time a connection is established with a client, it will occupy a resource on its own operating system
It can only establish a connection with one client in the same time period
Socket based on UDP protocol (UDP is unconnected, whichever end is started first will not report an error)
Usage case:
server side:
import socket ser = socket.socket(type=socket.SOCK_DGRAM) ser.bind ('127.0.0.1 '8888) mes,addr = ser.recvfrom(1024) print(mes.decode('utf-8')) ser.sendto('One Piece'.encode('utf-8'), addr) ser.close()
client side:
import socket client = socket.socket(type=socket.SOCK_DGRAM) addr = ('127.0.0.1', 8888) client.sendto('onepiece'.encode('utf-8'),addr) mess,addr = client.recvfrom(1024) print(mess.decode('utf-8')) client.close()
Although there is no problem in writing this way, it is not pythonic based on the need to encode and decode back and forth. In order to solve this problem, we specially write a subclass for the built-in socket class to solve the problem of encoding conversion.
Create class method:
from socket import * class Mysocket(socket): def __init__(self,coding='utf-8'): self.coding = coding super().__init__(type=SOCK_DGRAM) def mysend(self,mess,addr): return self.sendto(mess.encode(self.coding),addr) def myrecv(self,num): mess,addr = self.recvfrom(num) return mess.decode(self.coding),addr
Create client and receiver
# server side from my_test import Mysocket # import this class from the file path ser = Mysocket () ser.bind ('127.0.0.1 '8888) mes, addr = ser.myrecv (1024) print (month) ser.mysend('One Piece', addr) ser.close() # user terminal from my_test import Mysocket client = Mysocket() addr = ('127.0.0.1', 8888) client.mysend('onepiece',addr) mess,addr = client.myrecv(1024) print(mess) client.close()
The time synchronization service of the client is completed based on the server under UDP. For example, all machines in the computer room will request the server at regular intervals to obtain a standard time.
# server side
import time import socket sk = socket.socket(type=socket.SOCK_DGRAM) ip_port = ('127.0.0.1',9200) sk.bind(ip_port) while True: msg,addr = sk.recvfrom(1024) # Received is the user-side format string bytecode sk.sendto(time.strftime(msg.decode('utf-8')).encode('utf-8'),addr) sk.close()
# client side
import socket import time tb = socket.socket(type=socket.SOCK_DGRAM) ip_port = ('127.0.0.1',9200) while True: tb.sendto('%Y/%m/%d %H:%M:%S'.encode('utf-8'),ip_port) mes,addr = tb.recvfrom(1024) print(mes.decode('utf-8')) time.sleep(1) tb.close()