Python socket network programming steps (socket used)

Source: Internet
Author: User

I. Socket
A socket is a network application provider that provides portable standard objects for specific network protocols (such as TCP/IP, ICMP/IP, and UDP/IP. They allow programs to accept and connect, such as sending and receiving data. To establish a communication channel, each endpoint of network communication has a socket object.
Sockets are part of the core of bsd unix systems, and they are also adopted by many other UNIX-like operating systems, including Linux. Many non-bsd unix systems (such as ms-dos, windows, OS/2, mac OS, and most host environments) provide socket support in the form of libraries.
The three most popular socket types are stream, datax, and raw. Stream and datax sockets can directly interface with the TCP protocol, while raw socket interfaces to the IP protocol. However, sockets are not limited to TCP/IP.

Ii. socket module

The socket module is a very simple object-based interface that provides access to the low-layer BSD socket style network. This module can be used to implement client and server sockets. To create a simple server with TCP and stream sockets in python, you need to use the socket module. Use the functions and class definitions contained in this module to generate programs that communicate over the network. Generally, it takes six steps to establish a server connection.

Step 2 is to create a socket object. Call the socket constructor.

Socket = socket. socket (familly, type)
The value of family can be AF_UNIX (Unix domain used for communication between processes on the same machine) or AF_INET (TCP and UDP for IPV4 protocol). As for the type parameter, SOCK_STREAM (stream socket), SOCK_DGRAM (Data PACKET socket), and SOCK_RAW (raw socket ).

Step 2 is to bind the socket (assigned) to the specified address, socket. bind (address)

Address must be a dual-element tuples (host, port), host name or IP address + port number. If the port number is being used or retained, or the host name or IP address is incorrect, A socke. error exception is thrown.

Step 2. After binding, you must prepare a socket to accept the connection request.

Socket. listen (backlog)
Backlog specifies the maximum number of connections, at least 1. After receiving the connection request, these requests must be queued. If the queue is full, the request is rejected.

Step 2: The server socket waits for the customer to request a connection through the socket accept method:
Connection, address = socket. accept ()
When the accept method is called, the socket enters the 'waiting' (or blocking) state. When a customer requests a connection, the method establishes a connection and returns it to the server. The accept method returns a tuples containing two elements, such as (connection, address ). The first element (connection) is a new socket object through which the Server communicates with the customer. The second element (address) is the customer's internet address.

Step 2 is the processing phase. The server and the customer communicate (transmit data) through the send and recv methods ). The server calls send and uses a string to send messages to the customer. The send method returns the number of sent characters. The server uses the recv method to receive information from the customer. When calling recv, you must specify an integer to control the maximum amount of data received by this call. The recv method enters the 'bucket' state when receiving data, and returns a string to indicate the received data. If the number of sent messages exceeds the recv limit, the data is truncated. The excess data is buffered at the receiver. When you call recv later, excess data will be deleted from the buffer.

Step 2: After the transmission ends, the server calls the close method of socket to close the connection.

It takes four steps to establish a simple customer connection.

Step 2: Create a socket to connect to the server socket = socket. socket (family, type)
Step 2: Use the socket connect method to connect to the server socket. connect (host, port ))
Step 2: the customer and the server communicate through the send and recv methods.
Step 2. After the end, the customer calls the close method of socket to close the connection.


To compile a server in python, follow these steps:

The first step is to create a socket object. Call the socket constructor. For example:
Socket = socket. socket (family, type)
The family parameter represents the address family, which can be AF_INET or AF_UNIX. The AF_INET family includes Internet addresses, and the AF_UNIX family is used for communication between processes on the same machine.
The type parameter represents the socket type, which can be SOCK_STREAM (stream socket) and SOCK_DGRAM (datagram socket ).

The second step is to bind the socket to the specified address. This is implemented through the bind method of the socket object:
Socket. bind (address)
The address of a socket created by AF_INET must be a dual-element tuple in the format of host and port ). Host indicates the host, and port indicates the port number. If the port is in use, the host name is incorrect, or the port is retained, the bind method will cause a socket. error exception.

Step 3: Use the listen method of socket to receive connection requests.
Socket. listen (backlog)
Backlog specifies the maximum number of customers allowed to connect to the server. The value must be at least 1. After receiving the connection request, these requests need to be queued. If the queue is full, the request is rejected.

Step 4: The server socket waits for the customer to request a connection through the socket accept method.
Connection, address = socket. accept ()
When the accept method is called, the socket enters the "waiting" status. When a customer requests a connection, the method establishes a connection and returns it to the server. The accept method returns a triple (connection, address) containing two elements ). The first element connection is the new socket object, and the server must communicate with the customer through it; the second element address is the customer's Internet address.

The fifth step is the processing phase. The server and client communicate (transmit data) through the send and recv methods ). The server calls send and uses a string to send messages to the customer. The send method returns the number of sent characters. The server uses the recv method to receive information from the customer. When calling recv, the server must specify an integer, which corresponds to the maximum data volume that can be received through this method call. The recv method enters the "blocked" status when receiving data, and returns a string that indicates the received data. If the amount of data sent exceeds the recv limit, the data will be truncated. The excess data is buffered at the receiving end. When recv is called in the future, excess data will be deleted from the buffer zone (and any other data that the customer may send since the last recv call ).
When the transmission ends, the server calls the socket close method to close the connection.


Follow these steps to write a client in python:

Create a socket to connect to the server: socket = socket. socket (family, type)
Use the connect Method of socket to connect to the server. For the AF_INET family, the connection format is as follows:
Socket. connect (host, port ))
Host indicates the server host name or IP address, and port indicates the port number bound to the server process. If the connection is successful, the customer can communicate with the server through the socket. If the connection fails, the socket. error exception will occur.
In the processing phase, the customer and server will communicate with the recv method through the send method.
After the transmission ends, the customer calls the close method of socket to close the connection.

The following is a simple example:

Server. py
Copy codeThe Code is as follows:
If _ name _ = '_ main __':
Import socket
Sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Sock. bind ('localhost', 8001 ))
Sock. listen (5)
While True:
Connection, address = sock. accept ()
Try:
Connection. settimeout (5)
Buf = connection. recv (1024)
If buf = '1 ':
Connection. send ('Welcome to server! ')
Else:
Connection. send ('please go out! ')
Failed t socket. timeout:
Print 'time out'
Connection. close ()


Client. py
Copy codeThe Code is as follows:
If _ name _ = '_ main __':
Import socket
Sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Sock. connect ("localhost", 8001 ))
Import time
Time. sleep (2)
Sock. send ('1 ')
Print sock. recv (1024)
Sock. close ()

Run server. py on the terminal, and then run clien. py. "welcome to server" will be printed on the terminal! ". If you change sock. send ('1') of client. py to another value, "please go out!" will be printed! ", If you change time. sleep (2) to a value greater than 5, the server will time out.

Example:
Server:
Copy codeThe Code is as follows:
# Socket server
# Obtain the socket construction and constants
From socket import *
# ''Indicates that the server is localhost
MyHost =''
# Listen on an unretained port number
MyPort = 50007
# Setting a TCP socket object
Sockobj = socket (AF_INET, SOCK_STREAM)
# Bind it to the port number
Sockobj. bind (myHost, myPort ))
# Listener. Five connections are allowed.
Sockobj. listen (5)
# The loop does not end until the process ends
While True:
# Waiting for the next client connection
Connection, address = sockobj. accept ()
# The link is a new socket
Print 'server connected by', address
While True:
# Read the next line of the client socket
Data = connection. recv (1024)
# Skip the loop if there is no quantity
If not data: break
# Send a reply to the client
Connection. send ('echo => '+ data)
# Eof When socket is disabled
Connection. close ()

Client:
Copy codeThe Code is as follows:
Import sys
From socket import *
ServerHost = 'localhost'
ServerPort = 50007
# Default text sent to the server
Message = ['Hello network world']
# If the parameter is greater than 1, the linked server is the first parameter.
If len (sys. argv)> 1:
ServerHost = sys. argv [1]
# If the parameter is greater than 2, the link text is the second parameter.
If len (sys. argv)> 2:
Message = sys. argv [2:]
# Create a TCP/IP socket object
Sockobj = socket (AF_INET, SOCK_STREAM)
# Connect to the server and Port
Sockobj. connect (serverHost, serverPort ))
For line in message:
# Send line to the server through a set of words
Sockobj. send (line)
# Data received from the server, up to 1 k
Data = sockobj. recv (1024)
# Confirm that it is referenced, Which is 'X'
Print 'client received ed: ', repr (data)
# Disable socket
Sockobj. close ()

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.