A simple python socket programming

Source: Internet
Author: User

To compile a server in python, follow these steps:

1.

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 ).
2.

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.
3.

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.
4.

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.
5. The fifth step is the processing stage. 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 ).
6. When the transfer is over, the server calls the close method of socket to close the connection.

Follow these steps to write a client in python:

1. Create a socket to connect to the server: socket = socket. socket (family, type)
2.

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.
3. In the processing phase, the customer and the server will communicate with the recv method through the send method.
4. After the transmission ends, the customer calls the close method of socket to close the connection.

The following is a simple example:

Server. py
Python code 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 ()
Copy client. py
Python code 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 ()
 

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.