Python network programming socket module

1. Network Protocol

  The network protocol is the rules, standards or conventions required for data exchange and transmission in the network. It is mainly composed of three elements: syntax (the structural form of data and information), semantics and synchronization (the implementation sequence of events).

  The first protocol theoretical model proposed in the world is the Open System Interconnection Basic Reference Model (OSI) proposed by the International Standards Organization (ISO), which adopts a seven-layer protocol architecture. Although OSI is clear and complete, it is not practical because it is complex and impractical. On the other hand, the TCP/IP protocol using the simplified OSI has been widely used. It is a four-layer architecture, including the application layer, the transport (transport) layer, the Internet (network) layer and the network interface. Floor.

application layer

(FTP、SMTP、HTTP等)

transport layer

(TCP、UDP)

Network layer

(IP)

network interface layer

 

TCP/IP protocol diagram

   The TCP/IP protocol is actually a protocol family, including not only TCP and IP protocols, but also UDP, FTP, HTTP, SMTP, etc., and also some protocols such as ICMP, ARP, and RARP that are not shown in the figure.

  This divided protocol structure also shows that the data that the upper-layer protocol needs to transmit should be handed over to its immediate lower layer. The application layer and transmission have two or more protocols respectively, so for the application layer, different protocol data can be transmitted through different protocols of the transport layer.

2. Socket module

  Both the TCP and UDP protocols in the TCP/IP protocol implement network functions through a socket called socket. A socket is a file-like object that enables programs to accept or establish connections to clients for sending and receiving data. Whether it is a client program or a server-side program, in order to perform network communication, a socket object must be created.

  In the Python standard library, using the socket object provided in the socket module, a server and a client can be established in a computer network and can communicate. The server needs to establish a socket object and wait for the connection from the client. The client uses the socket object to connect with the server. Once the connection is successful, the client and server can communicate.

  The socket object in the socket module is the basic object of socket network programming, and its initialization prototype

  socket(family,type,proto)

  The meaning of its parameters:

  family: address family, optional parameter. Default AF_INET (IPv4), can also be AF_INET6 or AF_UNIX;

  type: socket type, optional parameter. Default SOCK_STREAM (TCP protocol), available SOCKET_DGRAM (UDP protocol);

  proto: protocol type, optional parameter. Default is 0.

  As the socket object on the server side, the following common methods are mainly used:

  1.bind(address)

  Its parameter address is a tuple consisting of IP address and port, such as '('127.0.0.1', 1051)' . If the IP address is empty, it means this machine. Its role is to use the socket to associate with the server address.

  2.listen(backlog)

  The parameter backlog specifies the maximum number of pending connections the operating system will allow it to before rejecting a connection. The minimum value is 0 (if the user uses a smaller value, it is automatically set to 0), and a maximum of 5 is sufficient for most programs.

  This method sets the socket to server mode, and then you can use the accept() method to wait for the connection from the client.

  3.accept()

  It waits for an incoming connection and returns a tuple of the newly created socket connection to the client and the client's address, which is also a tuple of the client's IP address and port.

  4.close()

  The function of this method is to close the socket. Stop the program's connection to the server or client.

  5.recv(buffersize[,flag])

  Used to accept the information sent by the remote connection and return the information, its type is bytes. buffersize can set the size of the buffer.

  6.send(data[,flags])

  Used to send information to the remote end of the connection, data should be data of type bytes. Its return value is the number of bytes transferred. The data length of its transmission has a certain limit.

  7.sendall(data[,flags])

  这个方法与send()方法相似,但是有时候在传输数据时,由于数据过多,用send()方法无法一次性传输,用sendall()方法可以解决这一问题,而sendall()也是通过循环运行send()方法来进行传输。

  而建立服务器端的socket就要依次使用这几个方法,其基本顺序为:

 

3.创建一个服务器端  

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 import socket
 4 
 5 sk = socket.socket() #创建socket对象
 6 address = ('127.0.0.1', 8001) 
 7 sk.bind(address) #绑定本机地址
 8 sk.listen(5) #监听
 9 print('waiting...')
10 conn,addr = sk.accept() #等待客户端连接
11 
12 while True:
13     #防止客户端异常关闭,导致服务器端程序出错
14     try: 
15         data = conn.recv(1024)
16     except Exception:
17         data = None
18     #当客户端传送的数据为空时,关闭服务器端与客户端之间的连接,等待其他客户端连接
19     if not data: 
20         conn.close()
21         conn,addr = sk.accept()
22         continue
23     print(str(data,  'utf8')) # 因为接收的数据类型为bytes,所以转换成字符串再打印
24      inp = input('>>>')
25     conn.send(bytes(inp, 'utf8')) #传送的数据类型应为bytes
26 
27 sk.close()

 

4.创建一个客户端

  相比用socket建立服务器端而言,建立客户端程序简单多了。当然还是需要创建一个socket的实例,而后调这个socket实例的connect()方法来连接服务器端即可。这个方法原型为:

  connect(address)

  参数address 通常也是一个元组(由一个主机名/IP地址,端口构成),当然要连接本地计算机的话,主机可直接使用'localhost',它用于将socket连接到远程以address为地址的计算机。

  用socket 建立客户端的基本流程:

  

代码实现:

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 import socket
 4 
 5 sk = socket.socket() #创建套接字
 6 address = ('127.0.0.1', 8001)
 7 sk.connect(address) # 与服务器端连接
 8 while True:
 9     inp = input('>>>')
10     if inp == 'exit':
11         break
12     sk.send(bytes(inp, 'utf8'))
13     data = sk.recv(1024)
14     print(str(data, 'utf8'))
15 
16 sk.close()

 

 

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325183272&siteId=291194637