Socket Is the application layer and TCP/IP Intermediate software abstraction layer for protocol family communication , It's a set of interfaces . In design mode ,Socket It's a facade pattern , It's complicated TCP/IP The protocol family is hidden in Socket The back of the interface , For users , A simple set of interfaces is all , Give Way Socket To organize data , To comply with the specified protocol .
In fact, it can be considered that ,socket It's just a module . We establish the connection and communication between the two processes by calling the methods already implemented in the module . Can also be socket Think it's ip+port, because ip It is used to identify the location of a host in the Internet , and port It's used to identify an application on this machine . So we just need to establish ip and port You can find an application , And use socket Module to communicate with .
2、socket（ Socket ） The development history and types of
Sockets originate 20 century 70 University of California, Berkeley version Unix, That's what people say BSD Unix. therefore , Sometimes people call sockets “ Berkeley socket ” or “BSD Socket ”. In the beginning, sockets were designed to be used with Communication between multiple applications on a host . This is also known as interprocess communication or IPC. There are two types of sockets （ Or there are two races , They are file based and network-based .
A family of sockets based on file types
The name of the socket family ：AF_UNIX
unix Everything is a document , File-based sockets call on the underlying file system to fetch data , Two socket processes run on the same machine , Communication can be done indirectly by accessing the same file system .
Socket family based on network type
The name of the socket family ：AF_INET
( also AF_INET6 Be used for ipv6, There are other address families , however , They are either used for a particular platform , Or it has been abandoned , Or it's rarely used , Or not at all , All address families ,AF_INET It's the most widely used one ,python Support many address families , But for network programming , Most of the time only use AF_INET)
3、TCP The protocol and UDP agreement
TCP（Transmission Control Protocol） reliable 、 Connection oriented protocol 、 Low transmission efficiency full duplex communication （ Send cache & Receive cache ）、 Byte stream oriented . Use TCP Application ：Web browser ; E-mail 、 File transfer program .
UDP（User Datagram Protocol） unreliable 、 Connectionless service , High transmission efficiency （ Little delay before sending ）, one-on-one 、 One to many 、 For one more 、 Many to many 、 Message oriented , Do your best to serve , No congestion control . Use UDP Application ： The domain name system (DNS); Video streaming ;IP voice (VoIP).
4、socket（ Socket ） The early use of
（1）、 be based on TCP Agreed socket
<1>、 Server side
import socket sk = socket.socket() # Creates a socket for the server sk.bind(('127.0.0.1',9001)) # Bind an address IP + port sk.listen() # Start listening for client requests # 127.0.0.1 Always identify the local address # But the switch You can get rid of some network problems in the process of writing code conn,addr = sk.accept() # Receive a connection request conn.send(b'hello') # Send messages to clients msg = conn.recv(1024).decode('utf-8') # Receive client information , And limit the number of bytes received print(msg) conn.close() # End the message with the other party sk.close() # Close the server socket
import socket sk = socket.socket() # Create a customer socket sk.connect(('127.0.0.1',9001)) # Try to connect to the server IP + port msg = sk.recv(23) # dialogue ( send out / receive ) print(msg) sk.send(' Hello '.encode('utf-8')) sk.close() # Close the client socket
Be careful ：
TCP It's connection based , The server side must be started first , Then start the client to connect to the server .
UDP It's disconnected , After starting the service, you can accept the message directly , There's no need to set up a link in advance .
# When you restart the server, you may encounter errors OSError： [Error 48] Address already in use # terms of settlement ： Join a socket To configure , reusing ip And port import socket from socket import SOL_SOCKET,SO_REUSEADDR sk = socket.socket() sk.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) # Join this sk.bind(('127.0.0.1',8898)) # Bind address to socket ···
（2）、 be based on UDP Agreed socket
<1>、 Server side
from socket import socket,SOCK_DGRAM sk = socket(type=SOCK_DGRAM) # Creates a socket for the server sk.bind(('127.0.0.1',9001)) # Bind the server socket while True: msg,cli_addr = sk.recvfrom(1024) # dialogue ( Receive and send ) print(msg.decode('utf-8')) msg = input('>>>') if msg.upper() == 'Q':continue sk.sendto(msg.encode('utf-8'),cli_addr)
from socket import socket,SOCK_DGRAM sk = socket(type=SOCK_DGRAM) server_addr = ('127.0.0.1',9001) while True: msg = input('>>>') if msg.upper() == 'Q': break sk.sendto(msg.encode('utf-8'),server_addr) msg = sk.recv(1024) print(msg.decode('utf-8'))
5、socket Detailed explanation
<1>、 establish socket Parameter description of object ：
|family||Address series should be AF_INET( The default value is ),AF_INET6,AF_UNIX,AF_CAN or AF_RDS. （AF_UNIX The domain actually uses local socket Files to communicate ）|
|type||Socket type should be SOCK_STREAM( The default value is ),SOCK_DGRAM,SOCK_RAW Or others SOCK_ One of the constants . SOCK_STREAM Is based on TCP Of , Guaranteed （ That is to ensure that the data is correctly transmitted to the other party ） Connection oriented SOCKET, For data transmission . SOCK_DGRAM Is based on UDP Of , Unprotected, message oriented socket, It is used to send broadcast information on the network .|
|proto||The agreement number is usually zero , It can be omitted , Or in the address family AF_CAN Under the circumstances , The agreement shall be CAN_RAW or CAN_BCM One of .|
|fileno||If you specify fileno, The other parameters are ignored , Causes the socket with the specified file descriptor to return . And socket.fromfd() Different ,fileno Will return the same socket , Instead of repeating . This may help to use socket.close() Turn off a separate outlet .|
<2>、 socket More ways to introduce
# Server socket function s.bind() # binding ( host , Port number ) To socket s.listen() # Start TCP monitor s.accept() # Passive acceptance TCP Customer connection ,( Blocking type ) Waiting for the connection # Client socket functions s.connect() # Active initialization TCP Server connection s.connect_ex() # connect() Extended version of function , Error code returned when error , Instead of throwing an exception # Socket functions for public use s.recv() # receive TCP data s.send() # send out TCP data s.sendall() # send out TCP data s.recvfrom() # receive UDP data s.sendto() # send out UDP data s.getpeername() # The address of the remote connection to the current socket s.getsockname() # The address of the current socket s.getsockopt() # Returns the parameters of the specified socket s.setsockopt() # Set the parameters of the specified socket s.close() # Close socket # Lock oriented socket method s.setblocking() # Set the blocking and non blocking mode of the socket s.settimeout() # Set the timeout for blocking socket operations s.gettimeout() # Get the timeout for blocking socket operations # File oriented socket functions s.fileno() # File descriptor for socket s.makefile() # Create a file related to the socket