Wu Yuxiong - born natural python learning Notes: Python3 Network Programming

Python offers two levels of access network services. : 

Low-level network services to support the basic Socket, which provides a standard BSD Sockets API, you can access all the methods underlying operating system Socket interface. 
A high level of network service module SocketServer, which provides server center class, you can simplify the development of a network server.
What is the Socket? 
The Socket also known as the " socket " , the application is usually by " socket " sent to the network request or response network request, or the hosts of processes on a computer that can communicate.
socket () function 
in Python, we use the socket () function to create a socket, syntax is as follows: 

socket.socket ([Family [, of the type [, proto]]]) 
Parameters 
family: the family can make AF_UNIX socket or AF_INET 
type: socket type may be connection-oriented or non-connected into SOCK_STREAM or SOCK_DGRAM 
Protocol: default is 0 is generally not filled.
Socket object (built-in) method 
function describes 
the server side socket 
s.bind () bind address (host, port) to the socket, at AF_INET, indicates the address tuple (host, port) form. 
s.listen () to start listening TCP. backlog specified before connection rejection, the operating system can suspend the maximum number of connections. The value of at least 1, most of the application is set to 5 on it. 
s.accept () passively accept TCP client connections (blocking) waiting for the arrival of connected 
client socket 
s.connect () initiative to initialize TCP server connections. The general format of address tuples (hostname, port), if the connection error, an error return socket.error. 
s.connect_ex () connect () function of an extended version, returns an error code when the error, rather than throwing an exception 
public use socket function 
s.recv () receives the TCP data, the data returned as a string, specify the bufsize of the maximum amount of data received. flag provides additional information about the message can usually be ignored. 
s.send () TCP data transmission, the transmission data string is attached to the socket. The return value is the number of bytes to be transmitted, this number may be smaller than the size in bytes of the string. 
s.sendall () to send TCP data integrity, complete TCP send data. The transmission data string is connected to the socket, but before returning tries to send all the data. Successful return None, failure exception is thrown.
s.recvfrom () receiving UDP data, similar to the recv (), but returns the value (data, address). Wherein the received data is a string containing the data, address data is the address of the sending socket.
s.sendto () to send UDP data, transmits the data to the socket, the form of address (ipaddr, port) tuple, the specified remote address. The return value is the number of bytes sent. 
S.CLOSE () closes the socket 
s.getpeername () returns the address of the connected remote socket. The return value typically tuple (ipaddr, port). 
s.getsockname () Returns the socket's own address. Usually a tuple (ipaddr, Port) 
s.setsockopt (Level, optname, value) set the options for a given value of the socket. 
s.getsockopt (level, optname [.buflen] ) returns the value of the socket option. 
s.settimeout (timeout) timeout period setting operation socket, timeout is a floating-point number, in seconds. Value None means no time-out period. In general, the time-out period should be set at the newly created socket connection as they may be used to operate (e.g., Connect ()) 
s.gettimeout () returns the current value of the timeout period, in seconds, if no time-out period, None is returned. 
s.fileno () Returns the 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 data can not be sent immediately, it will cause abnormal socket.error. 
s.makefile () to create a file associated even with the socket
Examples of simple 
server 
we use socket module socket function to create a socket object. socket object can be set via a socket service call other functions. 

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

Then, we call the accept method of socket objects. The method waits for the client connection, and returns the connection object representing the connection is to the client. 

The complete code is as follows: 
# import socket, sys module 
Import socket
 Import SYS 

# Create a socket object 
serversocket = socket.socket ( 
            socket.AF_INET, socket.SOCK_STREAM) 

# get the local hostname 
Host = socket.gethostname () 

Port = 9999 # Bind port number ServerSocket.bind ((Host, port)) # set the maximum number of connections, more than queuing




 
serversocket.listen (5) 

The whileTrue:
     # clients connect 
    ClientSocket, addr = ServerSocket.accept ()       

    Print ( " connection address:% S " % str (addr)) 
    
    msg = ' Welcome to the rookie tutorial! ' + " \ R & lt \ n- " 
    clientsocket.send (msg.encode ( ' UTF-. 8 ' )) 
    clientsocket.close ()
The client 
then we write a simple client to connect to the service instance created above. Port number is 9999 . 

socket.connect (hosname, port) method opens a TCP connection to the host for the hostname port to port service providers. After connecting we can get 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! 
# File name: client.py 

# import socket, sys module 
Import socket
 Import SYS 

# Create a socket object 
S = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 

# get local hostname 
host = socket.gethostname () 

# set the port number 
port = 9999 # connection service, specified host and port s.connect ((host, port)) # receiving less than 1024 bytes of data 
msg = s.recv (1024




)

S.CLOSE () 

Print (msg.decode ( ' UTF-. 8 ' )) 
Now we open the two terminals, the first terminal performs a file server.py: 

$ to python3 server.py 
second terminal performs client.py file: 

$ python3 client.py 
Welcome to the rookie tutorial! 
Then we open the first terminal again, you will see the following information is output: 

connection address: ( ' 192.168.0.118 ' , 33397)
Python Internet modules 
following is a list of some important Python Network Programming modules: 

protocol functions Python module use port number 
HTTP Web access     80     httplib, urllib, xmlrpclib 
NNTP reading and posting news articles, commonly known as " Post "     119     nntplib 
the FTP file transfer     20     ftplib , urllib 
the SMTP send mail     25     smtplib 
POP3 receiving mail     110     poplib 
IMAP4 e-mail to obtain     143     imaplib 
the Telnet command line     23     telnetlib 
Gopher information to find     70 gopherlib, urllib

 

Guess you like

Origin www.cnblogs.com/tszr/p/12008488.html