Python Network programming Socket module

Source: Internet
Author: User

1. Network Protocols

Network protocol is the rules, standards or conventions for data exchange and transmission in the network, and the utility consists of three elements: syntax (the structure of data and information), semantics and synchronization (sequence of events).

  The first proposed protocol model in the world is the basic Reference Model for Open Systems Interconnection (OSI), proposed by the International Standards Organization (ISO), which adopts the architecture of the seven-layer protocol. Although the OSI is clear and complete, it is not practical to be complex and impractical. On the other hand, the use of the simplified OSI TCP/IP protocol has been widely used, it is a four-tier architecture, including the application layer, transport (transmission) Transport layer, the Internet (network) layer and the interface layer.

Application Layer

(FTP, SMTP, HTTP, etc.)

Transport Layer

(TCP, UDP)

Network layer

(IP)

Network interface Layer

TCP/IP protocol diagram

The TCP/IP protocol is actually a protocol cluster that includes not only TCP and IP protocols, but also UDP, FTP, HTTP, SMTP, and so on, including ICMP, ARP, RARP and other protocols not shown in the diagram.

This partitioned protocol structure also shows that the data that the upper layer protocol needs to transmit should be handed to its immediate lower level. The application layer and the transmission have more than two protocols, so for the application layer, different protocol data can be transmitted through different protocols of the transport layer.

2. Socket Module

TCP and UDP protocols in the TCP/IP protocol are all connected by a socket (socket) to achieve network functionality. A socket is a class file object that enables a program to accept a connection to a client or establish a connection to a client to send and receive data. The socket object is created for network communication, whether it is a client program or a server-side program.

In the Python standard library, the socket object provided in the socket module can be used to establish the server and client in the computer network and to communicate. The server side needs to establish a socket object and wait for the client to connect. The client uses the socket object to connect to the server side, and once the connection is successful, the client and the service side can communicate.

The socket object in the socket module is the base object of the socket network programming, and its initialization prototype

Socket (Family,type,proto)

Its parameter meaning:

Family: Address family, optional parameters. The default af_inet (IPV4) can also be af_inet6 or Af_unix;

Type:socket type, optional parameter. Default Sock_stream (TCP protocol), available Socket_dgram (UDP protocol);

Proto: protocol type, optional parameter. The default is 0.

As a server-side socket object, the following common methods are used mainly:

1.bind (Address)

Its parameter address is a tuple of IP addresses and ports, such as ' (' 127.0.0.1 ', 1051) '. If the IP address is empty, the native is represented. It is used to associate the socket with the server address.

2.listen (Backlog)

The parameter backlog specifies the maximum number of pending connections that the operating system allows before refusing to connect. A minimum value of 0 (which is automatically set to 0 if the user uses a smaller value) is sufficient for most programs to have a maximum of 5.

This method sets the socket to server mode, after which the accept () method can be electrophoresis to wait for the client to connect.

3.accept ()

It waits for the incoming connection and returns a tuple of the new client's socket connection and client address, and the client's address is a tuple of client IP addresses and ports.

4.close ()

The function of this method is to close the socket. Stop the program from connecting to the server or client.

5.RECV (Buffersize[,flag])

Used to accept information sent from a remote connection and return that information, which is of type bytes. BufferSize can set the size of the buffer.

6.send (Data[,flags])

Used to send information to the far end of a connection, data should be of type bytes. Its return value is a transmitted number of bytes. The length of the data transmitted has a certain limit.

7.sendall (Data[,flags])

This method is similar to the Send () method, but sometimes when the data is transferred, because of too much data, the Send () method can not be transmitted one time, with the Sendall () method to solve the problem, and Sendall () is also through the loop to run the Send () method to transport.

and the establishment of the server-side socket to use these methods in turn, the basic sequence is:

 

3. Create a server-side
1 #!/usr/bin/python2 #-*-coding:utf-8-*-3 ImportSocket4 5SK = Socket.socket ()#creating a Socket object6Address = ('127.0.0.1', 8001) 7Sk.bind (Address)#bind the machine address8Sk.listen (5)#Monitor9 Print('Waiting ...')TenCONN,ADDR = Sk.accept ()#Waiting for client connections One  A  whileTrue: -     #prevents the client from shutting down abnormally, causing a server-side program error -     Try:  thedata = CONN.RECV (1024) -     exceptException: -data =None -     #when the data sent by the client is empty, the connection between the server side and the client is closed, waiting for other clients to connect +     if  notData: - conn.close () +CONN,ADDR =sk.accept () A         Continue at     Print(Str (data,'UTF8'))#because the received data type is bytes, it is converted to a string and then printed -INP = input ('>>>') -Conn.send (Bytes (INP,'UTF8'))#the data type to be transferred should be bytes -  -Sk.close ()

4. Create a client

It is much simpler to build a client-side program than to set up a server with a socket. Of course, you need to create an instance of the socket, and then tune the socket instance's connect () method to connect to the server side. The prototype for this method is:

Connect (address)

The address of the parameter is usually also a tuple (consisting of a hostname/IP address, a port), of course, to connect to the local computer, the host can directly use ' localhost ', which is used to connect the socket to a remote address-based computer.

The basic process for establishing a client with a socket:

  

Code implementation:

1 #!/usr/bin/python2 #-*-coding:utf-8-*-3 ImportSocket4 5SK = Socket.socket ()#Creating Sockets6Address = ('127.0.0.1', 8001)7Sk.connect (Address)#connection to server side8  whileTrue:9INP = input ('>>>')Ten     ifINP = ='Exit': One          Break ASk.send (Bytes (INP,'UTF8')) -data = SK.RECV (1024) -     Print(Str (data,'UTF8')) the  -Sk.close ()

  

Python Network programming Socket module

Related Article

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.