What is a network?
The network is composed of nodes and lines, representing many objects and their interconnections. In mathematics, a network is a graph, which is generally thought to refer specifically to weighted graphs. In addition to the mathematical definition of the network, there is a specific physical meaning, that is, the network is a kind of the same type of practical problems abstracted from the model. In the computer domain, the network is the information transmission, the reception, the sharing virtual platform, through it links each point, the surface, the body information together, thus realizes these resources sharing. The network is the most important invention in the history of human beings, which improves the development of science and technology and human society.
Three elements of network communication
IP Address
Used to represent a single host
Special IP address 127.0.0.1 or localhost (for local loopback address, reserved address, etc.), can be used for native testing
Port number
to send data to an application specified by each other, the network applications are identified with numbers in order to identify those applications. To address these numbers conveniently, call these numbers the ports
Transport protocol
TCP protocols: Transmission Control Protocol
Connection-oriented: connections need to be established before transmission
A large amount of data transfer during the connection process
Three times handshake connection, belong to secure reliable connection
Slow transmission rate, low efficiency
UDP protocol: User Transfer Protocol
Non-connection oriented: Transfer process does not need to establish a connection to transmit
The size of each data transfer is limited to 64K
The transmission process is unreliable
Fast transmission rate, high efficiency
Socket Network Programming
As a simple implementation of a Web applet
Import Socket
def handle_request (client):
buf = CLIENT.RECV (1024)
client.send (bytes ("http/1.1 \ r \ n, ' UTF8 ')
client.send (Bytes ("Hello, World", ' UTF8 ')
def Main ():
sock = Socket.socket (socket.af_ INET, Socket. SOCK_STREAM)
sock.bind ((' localhost ', 8080))
Sock.listen (5)
while True:
connection, address = Sock.accept ()
handle_request (connection)
Connection.close ()
if __name__ = = ' __main__ ':
Main ()
Python provides two levels of access to network services:
Low-level network services support basic sockets, which provide a standard BSD Sockets API that can access all the methods of the underlying operating system Socket interface.
High-level Network Service Module Socketserver, which provides a server-centric class that simplifies the development of network servers.
What is a socket?
The socket is also referred to as a socket, where an application usually sends a request to the network through a "socket" or answers a network request, allowing communication between processes on the host or on one computer.
Socket () function:
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 a connection-oriented or a non-connection
Protocol: Generally do not fill in the default of 0.
Communication process
###### #server端 ##########
import socket
SK = Socket.socket () address
= (' 127.0.0.1 ', 8000)
Sk.bind ( Address)
Sk.listen (3)
while true:
conn, addr = Sk.accept () while
true:
try:
data = CONN.RECV (1024)
print (str (data, ' UTF8 '))
if not data:
break
INP = input (">>>")
Conn.send (Bytes (INP, ' UTF8 '))
except Exception:
break
conn.close ()
######### #Client端 ######## ###
Import socket
SK = Socket.socket () address
= (' 127.0.0.1 ', 8000)
Sk.connect (address)
While True:
INP = input (">>>")
if InP = = "Exit": Break
sk.send (bytes (INP, ' UTF8 ')
) data = SK.RECV (1024)
print (str (data, ' UTF8 '))
Sk.close ()
Socket Built-in method
The S.bind () binding address (Host,port) to the socket, under Af_inet, in the form of a tuple (host,port) to represent the address.
S.listen () starts TCP listening. Backlog Specifies the maximum number of connections the operating system can suspend before rejecting a connection. The value is at least 1, and most applications are set to 5.
S.accept () passively accepts TCP client connections, (blocking) waiting for connection arrival <br>
Client sockets
S.connect () initiates the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if the connection fails.
S.CONNECT_EX () Extended version of the Connect () function, which returns an error code when an error occurs, rather than throwing an exception <br>
Socket functions for public use
S.RECV () Receives TCP data, the data is returned as a string, bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can often be ignored.
S.send () sends the TCP data to send the data in 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 completely and sends TCP data in full. Sends the data in a string to the attached socket, but attempts to send all the data before returning. Returns none successfully, and throws an exception if it fails.
S.recvform () 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 that sends the data.
S.sendto () sends the UDP data, sends the data to the socket, the address is a tuple in the form (Ipaddr,port), and specifies the remote location. 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 usually a tuple (ipaddr,port).
S.getsockname () returns the socket's own address. is usually 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 time-out period for a socket operation, timeout is a floating-point number, in seconds. A value of None indicates no time-out period. Typically, the timeout period should be set when the socket is just created, because they may be used for connected operations (such as Connect ())
S.gettimeout () Returns the value of the current time-out period, in seconds, or none if no time-out period is set.
S.fileno () returns the file descriptor for the socket.
S.setblocking (flag) If the flag is 0, the socket is set to non-blocking mode, otherwise the socket is set to blocking mode (default). In non-blocking mode, if the call to Recv () does not find any data, or the Send () call does not immediately send the data, the Socket.error exception is caused.
S.makefile () Creates a file associated with this socket
Instance
######## #Server端 ########## Import socket import subprocess SK = Socket.socket () address = (' 127.0.0.1 ', 8000) Sk.bind (a ddress) Sk.listen (3) while true:conn, addr = Sk.accept () while True:try:data = CONN.RECV (1024) except except Ion:break if not data:break # print (str (data, ' UTF8 ')) # data = str (data, ' UTF8 ') #解码同decode obj = Subproc Ess. Popen (Data.decode (' UTF8 '), shell=true, stdout=subprocess. PIPE) Ssh_result = Obj.stdout.read () Result_len = bytes (str (len (ssh_result)), ' UTF8 ') conn.send (Result_len) conn.s End (Ssh_result) conn.close () ######## #Client ######### import Socket SK = Socket.socket () address = (' 127.0.0.1 ', 800
0) Sk.connect While TRUE:INP = input (">>>") if InP = = "Exit": Break Sk.send (Bytes (INP, ' UTF8 ')) Result_len = Int (str (SK.RECV (1024), ' UTF8 ') print (result_len) data = bytes () while Len (data)!= RESULT_LEN:RECV = s
K.RECV (1024) data + + recv print (str (data, ' GBK ')) Sk.close ()
File Upload
Server
Import socket
import os
sk = Socket.socket () address
= (' 127.0.0.1 ', 8000)
Sk.bind
Sk.listen (3)
Base_dir = Os.path.dirname (Os.path.abspath (__file__))
while True:
conn, addr = Sk.accept () While
True:
data = CONN.RECV (1024)
cmd, file_name, file_size = str (data, ' UTF8 '). Split (' | ')
Path = Os.path.join (Base_dir, ' model ', file_name)
file_size = Int (file_size)
f = open (path, ' ab ')
Has_ recv = 0 while
has_recv!= file_size:
data = CONN.RECV (1024)
f.write (data)
HAS_RECV + len (data) C21/>f.close ()
Client
Import socket
import os
sk = Socket.socket () address
= (' 127.0.0.1 ', 8000)
Sk.connect
Base_dir = Os.path.dirname (Os.path.abspath (__file__)) while
True:
INP = input (">>>>"). Strip ()
path = Os.path.join (Base_dir, INP)
file_name = os.path.basename (path)
file_size = os.stat (path). st_size
file_info = ' post|%s|%s '% (file_name, file_size)
sk.sendall (bytes (file_info, ' UTF8 '))
f = open (path, ' RB ')
has_sent = 0 while
has_sent!= file_size:
data = f.read (1024)
sk.sendall (data)
has_sent + len (data)
f.close ()
print ("Upload succeeded")
Socketserver
The Socketserver module simplifies the task of the Network programming service, while the Socketserver module is also the basis for many server frameworks in the Python standard library.
The best way to learn it is to browse through its source code.
First, let's take a look at how to use
Import Socketserver
class MyServer (Socketserver. Baserequesthandler):
def handle (self):
print (server-side startup) while
True:
conn = Self.request
while True:
data = CONN.RECV (1024)
print (str (data, ' UTF8 '))
INP = input (">>>>>")
Conn.sendall (Bytes (INP, ' UTF8 '))
conn.close ()
if __name__ = = ' __main__ ':
server = Socketserver. Threadingtcpserver ((' 127.0.0.1 ', 8080), MyServer)
server.serve_forever ()
server
Import socket
SK = Socket.socket () address
= (' 127.0.0.1 ', 8080)
sk.connect (address)
print (" Client Startup "While
True:
INP = input (" >>>>> ")
sk.sendall (bytes (INP, ' UTF8 '))
if InP = = "Q":
break
data = SK.RECV (1024)
print (str (data, ' UTF8 '))
Sk.close ()
This code simply implements the ability of the server side to chat with multiple client simultaneously.
Before we look at the source, the first thing to be clear is that it is divided into several classes and the functional role of each class.
There are five classes in a inheritance diagram, four of which represent
Synchronous servers of four types:
The following is not a detailed said, want to understand more thoroughly, or look at the source bar.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.