Latest web development tutorials

Python3 network programming

Python offers two levels of access network services. :

  • Low-level network services to support basic Socket, it provides a standard BSD Sockets API, you can access all of the methods of the underlying operating system Socket interface.
  • A high level of network service module SocketServer, it provides a central server class, you can simplify the development of the network server.

What is Socket?

Socket also known as "socket", the application is usually issued by a "socket" to the network request or response network request, so that the process between hosts or between a computer on can communicate.


socket () function

Python, we use the socket () function to create a socket, syntax is as follows:

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

parameter

  • family: the family can make a socket or AF_INET AF_UNIX
  • type: Socket type can be connection-oriented or connectionless into SOCK_STREAM or SOCK_DGRAM
  • protocol: Generally not fill defaults to zero.

Socket object (built-in) method

function description
Server socket
s.bind () Bind address (host, port) to the socket at AF_INET, in the form of a tuple (host, port) indicates the address.
s.listen () Start TCP listening. backlog specified before rejecting the connection, the operating system can suspend the maximum number of connections. This value is at least 1, most applications can be set to 5.
s.accept () Passive acceptance of TCP client connections (blocking) waiting for the arrival of
Client socket
s.connect () Active initialize TCP server connections. General address of the format of tuples (hostname, port), if the connection error, an error is returned socket.error.
s.connect_ex () connect () extended version of the function returns an error code when an error instead of throwing an exception
Socket functions public purposes
s.recv () Receive TCP data, the data is returned as a string, specify the maximum amount of data to be received bufsize. Provide additional information about the message flag can usually be ignored.
s.send () Send TCP data, sends the data string to the socket connection. The return value is the number of bytes to send, this number may be less than the string of bytes.
s.sendall () Complete sending TCP data, complete transmit TCP data. It sends the data string to the socket connection, but before returning will try to send all the data. Successful return None, failure exception is thrown.
s.recvform () Receiving UDP data () is similar to recv, but the return value is (data, address). Wherein the data is a string containing the received data, address data is sent socket address.
s.sendto () Send UDP data, send data to a socket, address is in the form of (ipaddr, port) tuple specified remote address. The return value is the number of bytes sent.
s.close () Close the socket
s.getpeername () Returns the connection socket remote address. The return value is usually a tuple (ipaddr, port).
s.getsockname () Returns the socket's own address. Usually a tuple (ipaddr, port)
s.setsockopt (level, optname, value) Set the value of a given socket option.
s.getsockopt (level, optname [.buflen]) The return value of the socket option.
s.settimeout (timeout) Set socket operation timeout period, timeout is a floating-point number, in seconds. None value indicates no time-out period. Generally, time-out period should just create a socket set, because they may be used to operate the connection (such as connect ())
s.gettimeout () Returns the value of the current time-out period, in seconds, if there is no set time-out period, returns None.
s.fileno () Returns a socket file descriptor.
s.setblocking (flag) If the flag is 0, the socket is set to non-blocking mode, otherwise the socket to blocking mode (the default value). Non-blocking mode, if you call recv () did not find any data, or send () call can not immediately send data, it would cause socket.error exception.
s.makefile () Create a relevant documents in connection with the socket

Simple example

Server

We use the socket modulesocket function to create a socket object.socket object can call other functions to set up a socket service.

Now we can specify the services by callingbind (hostname, port) functionport (port).

Next, we call the acceptmethod of socket objects. The method waits for the client connection and returnconnectionobject that represents connected to the client.

The complete code is as follows:

#!/usr/bin/python3
# 文件名:server.py

# 导入 socket、sys 模块
import socket
import sys

# 创建 socket 对象
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM) 

# 获取本地主机名
host = socket.gethostname()

port = 9999

# 绑定端口
serversocket.bind((host, port))

# 设置最大连接数,超过后排队
serversocket.listen(5)

while True:
    # 建立客户端连接
    clientsocket,addr = serversocket.accept()      

    print("连接地址: %s" % str(addr))
    
    msg='欢迎访问本教程!'+ "\r\n"
    clientsocket.send(msg.encode('utf-8'))
    clientsocket.close()

Client

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

socket.connect (hosname, port) method opens a TCP connection to the host for thehostnameport toportservice providers.Once connected we can post-data from the server, remember, after the completion of the operation need to close the connection.

The complete code is as follows:

#!/usr/bin/python3
# 文件名:client.py

# 导入 socket、sys 模块
import socket
import sys

# 创建 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# 获取本地主机名
host = socket.gethostname() 

# 设置端口好
port = 9999

# 连接服务,指定主机和端口
s.connect((host, port))

# 接收小于 1024 字节的数据
msg = s.recv(1024)

s.close()

print (msg.decode('utf-8'))

Now we even have to open the terminal, the first terminal performs server.py file:

$ python3 server.py

The second terminal performs client.py file:

$ python3 client.py 
欢迎访问本教程!

This is our first and then open a terminal, you will see the following information is output:

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

Python Internet modules

Here are some important module Python network programming:

protocol Useful function The port number Python Modules
HTTP Web access 80 httplib, urllib, xmlrpclib
NNTP Reading and posting news articles, known as the "post" 119 nntplib
FTP file transfer 20 ftplib, urllib
SMTP send email 25 smtplib
POP3 incoming mail 110 poplib
IMAP4 Get Mail 143 imaplib
Telnet Command Line twenty three telnetlib
Gopher Find information 70 gopherlib, urllib

More details can be found in the official website of the Python the Socket Library and the Modules .