Socket network programming in python

Source: Internet
Author: User
This article mainly introduces Socket network programming in python, which has some reference value. if you are interested, please refer to it. What is network?

A network is composed of nodes and connections, indicating many objects and their intercommunication. In mathematics, the network is a type of graph, which is generally regarded as a weighted graph. In addition to mathematical definitions, the network also has a specific physical meaning, that is, the network is a model abstracted from some practical problems of the same type. In the computer field, the network is a virtual platform for information transmission, receiving, and sharing. it connects the information of various points, faces, and bodies to achieve the sharing of these resources. Network is the most important invention in the history of human development, improving the development of science and technology and human society.

Three elements of network communication

IP address
Used to represent an independent host
The special IP address 127.0.0.1 or localhost (indicating the local loopback address, reserved address, etc.) can be used for local testing.

Port number
To send data to the application specified by the peer, network applications are identified by numbers to identify these applications. These numbers are called ports for convenience.

Transmission Protocol
TCP protocol:Transmission Control Protocol
Connection-oriented: establish a connection before transmission
Massive data transmission during connection
The three-way handshake is a secure and reliable connection.
Low transmission rate and efficiency
UDP protocol:User transmission protocol
Connection-free: you can transmit data without establishing a connection during transmission.
The size of each data transmission is limited to 64 KB
Unreliable transmission
Fast transmission rate and high efficiency

SOCKET network programming

For example, simply implementing a WEB applet

import socketdef handle_request(client): buf = client.recv(1024) client.send(bytes("HTTP/1.1 200 OK\r\n\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 network services for access:

Low-level network services support basic Sockets. It provides the standard BSD Sockets API and can access all the methods of Socket interfaces of the underlying operating system.
SocketServer, a high-level network service module, provides a server center class to simplify the development of network servers.

What is socket?

Socket, also known as "Socket", usually uses "Socket" to send a request to or respond to a network request, so that processes on a host or computer can communicate with each other.

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 based on whether it is connection-oriented or not.
Protocol: Generally, the default value is 0.

Communication process

####### Server ########## import socketsk = socket. socket () address = ('2017. 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 indium = input (">>>") conn. send (bytes (indium, 'utf8') failed t Exception: breakconn. close () ########## Client ########### import socketsk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. connect (address) while True: indium = input (">>>") if indium = "exit": break sk. send (bytes (indium, 'utf8') data = sk. recv (1024) print (str (data, 'utf8') sk. close ()

Socket built-in method

S. bind (): bind the address (host, port) to the socket. in AF_INET, the address is expressed in the form of a tuples (host, port.
S. listen () starts TCP listening. Backlog specifies the maximum number of connections that the operating system can suspend before a connection is denied. This value must be at least 1, and most applications can be set to 5.
S. accept () passively accepts TCP client connections and waits for the connection to arrive.

Client socket
S. connect () actively initializes the TCP server connection ,. Generally, the format of address is tuples (hostname, port). If a connection error occurs, the socket. error is returned.
Extended version of s. connect_ex () connect () function. an error code is returned when an error occurs, instead of throwing an exception.

Common Socket functions
S. recv () receives TCP data, and the data is returned as a string. bufsize specifies the maximum data volume to receive. Flag provides other information about messages, which can be ignored.
S. send () sends TCP data and sends the data in string to the connected socket. The returned value is the number of bytes to be sent, which may be smaller than the size of the string.
S. sendall () completely sends TCP data, and completely sends TCP data. Send data in string to the connected socket, but try to send all data before returning. If None is returned successfully, an exception is thrown.
S. recvform () receives UDP data, which is similar to recv (), but returns (data, address ). Data is the string containing the received data, and address is the socket address for sending data.
S. sendto () sends UDP data and sends the data to the socket. The address is a tuples in the form of (ipaddr, port) and specifies the remote address. The returned value is the number of bytes sent.
S. close () close socket
S. getpeername () returns the remote address of the connection socket. The returned value is usually a tuples (ipaddr, port ).
S. getsockname () returns the address of the socket itself. It 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 superperiod of socket operations. timeout is a floating point number, measured in seconds. If the value is None, there is no superperiod. Generally, it should be set when the socket is just created during off-peak periods, because they may be used for connection operations (such as connect ())
S. gettimeout () returns the value of the current superperiod in seconds. If no superperiod is set, None is returned.
S. fileno () returns the file descriptor of 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 no data is found when recv () is called, or the send () call cannot send data immediately, a socket. error exception occurs.
S. makefile () creates a file related to the socket

Instance


######### Server ########## import socketimport subprocesssk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. bind (address) sk. listen (3) while True: conn, addr = sk. accept () while True: try: data = conn. recv (1024) failed t Exception: break if not data: break # print (str (data, 'utf8') # data = str (data, 'utf8 ') # decode the same as decode obj = subprocess. 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. send (ssh_result) conn. close () ######### Client ######### import socketsk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. connect (address) while True: indium = input (">>>") if indium = "exit": break sk. send (bytes (indium, 'utf8') result_len = int (str (sk. recv (1024), 'utf8') print (result_len) data = bytes () whil E len (data )! = Result_len: recv = sk. recv (1024) data + = recv print (str (data, 'gbk') sk. close ()

File Upload

Server

import socketimport ossk = socket.socket()address = ('127.0.0.1', 8000)sk.bind(address)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)  f.close()

Client

Import socketimport ossk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. connect (address) BASE_DIR = OS. path. dirname (OS. path. abspath (_ file _) while True: indium = input (">>>> "). strip () path = OS. path. join (BASE_DIR, indium) 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_se Nt = 0 while has_sent! = File_size: data = f. read (1024) sk. sendall (data) has_sent + = len (data) f. close () print ("uploaded successfully ")

Socketserver

The socketserver module simplifies the tasks of network programming service programs, and the SocketServer module is also the basis of many server frameworks in the Python standard library.

The best way to learn about it is to browse its source code.

First, let's take a look at how to use

Import socketserverclass MyServer (socketserver. baseRequestHandler): def handle (self): print ("server startup") while True: conn = self. request while True: data = conn. recv (1024) print (str (data, 'utf8') indium = input (">>>>") conn. sendall (bytes (indium, 'utf8') conn. close () if _ name _ = '_ main _': server = socketserver. threadingTCPServer ('2017. 0.0.1 ', 8080), MyServer) server. serve_forever () server

Import socketsk = socket. socket () address = ('2017. 0.0.1 ', 8080) sk. connect (address) print ("client startup") while True: indium = input (">>>>") sk. sendall (bytes (indium, 'utf8') if indium = "q": break data = sk. recv (1024) print (str (data, 'utf8') sk. close ()

This code allows the server to chat with multiple clients at the same time.

Before looking at the source code, we should first make it clear that it divides several classes and the functions of each class.

There are five classes in an inheritance dives, four of which represent
Synchronous servers of four types:

For more articles about Socket network programming in python, refer to PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.