Python network programming

Python provides two levels of access to the network service.

  • Low-level network services support the basic Socket, which provides a standard BSD Sockets API that provides full access to the underlying operating system Socket interface.
  • A high-level network service module, SocketServer, provides a server hub class that simplifies the development of network servers.

What is Socket?

Socket is also known as a socket, and applications typically use sockets to make or respond to network requests to the network, allowing communication between hosts or processes on a computer.


socket() function

In Python, we use the socket() function to create sockets in the following syntax format:

socket.socket([family[, type[, proto]]])

Parameters

  • Family: The socket family can make AF_UNIX or AF_INET
  • Type: The socket type can be divided into a connection-oriented or SOCK_STREAM or SOCK_DGRAM
  • Protocol: Generally do not fill in the default of 0.

The Socket object (built-in) method

Function Describe
The server-side socket
s.bind() The binding address (host, port) to the socket, AF_INET under AF_INET, represents the address in the form of a metagroup (host, port).
s.listen() Start TCP listening. B acklog specifies the maximum number of connections that the operating system can suspend before denying a connection. The value is at least 1, and most applications set it to 5.
s.accept() Passively accept the TCP client connection, (blocking) waiting for the connection to arrive
The client socket
s.connect() Active initialization of TCP server connections. The general address is in the form of a metagroup (hostname, port), and if the connection goes wrong, an socket.error error is returned.
s.connect_ex() An extended version of the connect() function that returns an error code when an error occurs, rather than throwing an exception
A common-purpose socket function
s.recv() Receives TCP data, which is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can often be ignored.
s.send() Sends TCP data, sends data from the string to the connected socket. Returns the number of bytes to send, which may be less than the byte size of the string.
s.sendall() Send TCP data in its entirety and TCP data in its entirety. S ends the data from the string to the connected socket, but attempts to send all the data before returning. None is returned successfully, and an exception is thrown if it fails.
s.recvform() Receive UDP data, similar to recv(), but with a return value of (data, address). Where data is the string that contains the received data, address is the socket address that sends the data.
s.sendto() Send UDP data, send data to sockets, address is a group in the form of (ipaddr, port), specifying a remote address. The return value is the number of bytes sent.
s.close() Close the socket
s.getpeername() Returns the remote address of the connection socket. The return value is usually a metagroup (ipaddr, port).
s.getsockname() Returns the socket's own address. Usually a metagroup (ipaddr, port)
s.setsockopt(level,optname,value) Sets the value of the given socket option.
s.getsockopt(level,optname[.buflen]) Returns the value of the socket option.
s.settimeout(timeout) Set the super-period of socket operation, timeout is a floating point in seconds. A value of None indicates that there is no super-period. In general, periods should be set when sockets are first created, as they may be used for connected operations such as connect()
s.gettimeout() Returns the value of the current super-period in seconds, or None if the super-period is not set.
s.fileno() Returns the file descriptor for the socket.
s.setblocking(flag) If flag is 0, the socket is set to non-blocking mode, otherwise the socket is set to blocking mode (the default). In non-blocking mode, an socket.error exception is caused if the call recv() does not find any data, or if the send() call does not send the data immediately.
s.makefile() Create a file that is related to the socket

A simple example

The service side

We use the socket function of the socket module to create an socket object. The socket object can set up an socket service by calling other functions.

Now we can specify the port (port) of the service by calling the bind (hostname, port) function.

Next, we call the accept method of the socket object. The method waits for the client to connect and returns the connection object, indicating that it is connected to the client.

The full code is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口
s.bind((host, port))        # 绑定端口

s.listen(5)                 # 等待客户端连接
while True:
    c, addr = s.accept()     # 建立客户端连接。
    print '连接地址:', addr
    c.send('欢迎访问W3Cschool教程!')
    c.close()                # 关闭连接

Client

Next we write a simple client instance to connect to the service created above. Port number is 12345.

The socket.connect (hosname, port) method opens a TCP connection to the host for the hostname port for the port provider. Once connected, we can take late data from the service side and remember that we need to close the connection when the operation is complete.

The full code is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口好

s.connect((host, port))
print s.recv(1024)
s.close()  

Now let's open a terminal, the first terminal executes server.py file:

$ python server.py

The second terminal executes client.py file:

$ python client.py 
欢迎访问W3Cschool教程!

This is the first terminal we open again, and you will see the following information output:

连接地址: ('192.168.0.118', 62461)

Python Internet module

Here are some important modules for Python network programming:

Agreement Functional useful The port number Python module
HTTP Web page access 80 httplib, urllib, xmlrpclib
NNTP Read and post news articles, commonly known as "posts" 119 nntplib
Ftp File transfer 20 ftplib, urllib
Smtp Send a message 25 smtplib
POP3 Receive the message 110 poplib
IMAP4 Get the message 143 imaplib
Telnet The command line 23 telnetlib
Gopher Information lookup 70 gopherlib, urllib

For more information, see Python Socket Library and Modules on the website.