Python Network Programming:
Python provides two levels of access to network services. :
The low-level network service supports the basic socket, which provides the standard BSD Sockets API to access all the methods of the underlying operating system socket interface.
The high-level Network Service module, Socketserver, provides a server-centric class that simplifies the development of network servers.
A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.
Socket () function to create a socket
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 sock_stream or sock_dgram depending on whether it is connection-oriented or non-connected
protocol: General does not fill the default is 0.
server-side sockets
S.bind () binds the address (host,port) to the socket and, under Af_inet, represents the address in the form of a tuple (host,port).
S.listen () starts TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection.
This value is at least 1, and most applications are set to 5.
s.accept () passively accepts TCP client connections, (blocking) waits for a connection to arrive
Client Sockets
S.connect () actively initializes the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection.
Extended version of the S.CONNECT_EX () connect () function, which returns an error code instead of throwing an exception when an error occurs
socket functions for public use
S.RECV () receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send () sends the TCP data, sending the data in the string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall () sends TCP data in full and sends TCP data in full. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
s.recvfrom () receives UDP data, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
s.sendto () sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), and specifies the remote address. The return value is the number of bytes sent.
s.close () Close socket
S.getpeername () returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
S.getsockname () returns the socket's own address. Typically a tuple (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) sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ())
S.gettimeout () returns the value of the current timeout, in seconds, or none if the timeout period is not set.
S.fileno () returns the file descriptor of the socket.
s.setblocking (flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to block mode (the default). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised.
S.makefile () Create a file associated with the socket
1!/usr/bin/python2 #-*-coding:utf-8-*-3 #file name: server.py4 5 ImportSocket#Importing the Socket module6 ImportCommands#Execute system Command Module7 8s = Socket.socket ()#creating a Socket object9Host = Socket.gethostname ()#get Local Host nameTenPort = 12345#Setting up Ports OneS.bind ((host, Port))#Binding Port AS.listen (5)#Waiting for client connections - - while1: theConn,addr=s.accept ()#accept the TCP connection and return the new socket with the IP address - Print'Connected by', addr#IP address of the output client - while1: -DATA=CONN.RECV (1024)#instantiate the received data +Cmd_status,cmd_result=commands.getstatusoutput (data)#The commands.getstatusoutput executes the system command (that is, the shell command), returns two results, the first is the state, the success is 0, and the second is the output information to execute the success or failure - ifLen (Cmd_result.strip ()) ==0:#if the output length is 0, the client is told to complete. This usage is for creating a file or directory, and there is no output information for a successful creation. +Conn.sendall ('Done .') A Else: atConn.sendall (Cmd_result)#Otherwise, the result is sent to the peer (i.e. the client) -Conn.close ()#Close Connection
server.py
server.py
!/usr/bin/python
#-*-Coding:utf-8-*-
# File Name: server.py
Import Socket # Importing Socket module
Import Commands #执行系统命令模块
s = Socket.socket () # Create socket Object
Host = Socket.gethostname () # Gets the local host name
Port = 12345 # setting ports
S.bind ((host, Port)) # bound Port
S.listen (5) # Waiting for client to connect
While 1:
Conn,addr=s.accept () #接受TCP连接 and returns the new socket with the IP address
print ' Connected by ', addr #输出客户端的IP地址
While 1:
Data=conn.recv (1024x768) #把接收的数据实例化
cmd_status,cmd_result=commands.getstatusoutput (data) # The commands.getstatusoutput executes the system command (that is, the shell command), returns two results, the first is the state, the success is 0, and the second is the output information to execute the success or failure
If Len (Cmd_result.strip ()) ==0: #如果输出结果长度为0, tell the client to finish. This usage is for creating a file or directory, and there is no output information for a successful creation.
Conn.sendall (' done. ')
Else:
Conn.sendall (Cmd_result) #否则就把结果发给对端 (i.e. client)
conn.close () #关闭连接
client.py
#!/usr/bin/python
#-*-Coding:utf-8-*-
# file name: client.py
Import Socket # Importing Socket module
s = Socket.socket () # Create socket Object
- Host = Socket.gethostname () # Gets the local host name
Port = 12345 # setting Ports good
S.connect ((host, Port))
While 1:
Cmd=raw_input ("Please input cmd:") #与人交互, enter the command
S.sendall (CMD) #把命令发送给对端
DATA=S.RECV (1024x768) #把接收的数据定义为变量
Print Data #输出变量
S.close () #关闭连接
Now we open two terminals, the first terminal executes the server.py file:
$ python server.py
The second terminal executes the client.py file:
$ python client.py
Welcome to the Novice Tutorial!
When we open the first terminal again, we will see the following information output:
Connection address: (' 192.168.0.118 ', 62461)
protocol function Use port number Python module
HTTP Web Access 80httplib, Urllib, Xmlrpclib
NNTP Read and post news articles, commonly known as "posts" 119nntplib
FTP file transfer 20ftplib, Urllib
SMTP Send mail 25smtplib
POP3 receiving mail 110poplib
IMAP4 Get Mail 143imaplib
telnet command line 23telnetlib
Gopher information Find 70gopherlib, Urllib
Python--socket