Detailed explanation of Python socket programming instances and python programming instances

Source: Internet
Author: User

Detailed explanation of Python socket programming instances and python programming instances

This example describes the Python socket programming in detail. Share it with you for your reference. The details are as follows:

Copy codeThe Code is as follows: sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
The above Code creates a socket object. The type parameter represents the socket type, which can be SOCK_STREAM (stream socket) and SOCK_DGRAM (datagram socket ). AF_INET indicates that the ip v4 type is created.
Copy codeThe Code is as follows: socket (address_family, type, protocol_type ):

The meanings of the preceding three parameters are as follows:

Address_family indicates the socket type to be created. Of course, the most common IP protocol is AF_INET. In unix systems, AF_UNIX is also commonly used to establish inter-process communication in unix systems.

Type is used to specify the communication type. Connection-oriented stream communication is usually established. SOCKET_DGRAM refers to packet communication. If address_family is set to AF_INET, it corresponds to TCP and UDP.

Protocol is used to specify the protocol type. This parameter is optional. When establishing tcp or udp connections, they are usually 0. If the first parameter is AF_INET, this parameter indicates the protocol field in the IP package.

[UDP does not distinguish between server and client. All nodes are equal]

Step 2: bind the socket to the specified address:
Copy codeThe Code is as follows: sock. bind ('localhost', 7556 ))
Step 3: Use the listen method to listen to requests: [the parameter in the listen method specifies the maximum number of accepted connections]
Copy codeThe Code is as follows: sock. listen (5)
Step 4: Keep receiving requests: After receiving connection requests, these requests need to be queued up. If the queue is full, the requests will be rejected.
Copy codeThe Code is as follows: connection, address = sock. accept ()
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 ).

If the sending succeeds, the buffer of the other party has the data you have sent.
# 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 ).

connection.settimeout(5)buf = connection.recv(1024)

The procedure is as follows:

      if buf == '1':  connection.send('welcome to python server!')else:  connection.send('please go out!')

Use send to send data to the client. The client uses recv to receive data.

import socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(('localhost',7556))import timetime.sleep(2)sock.send('1')print sock.recv(1024)sock.close()

This is the entire communication process.

The Code is as follows:

Server:

#!/usr/bin/env pythonimport socketsock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)sock.bind(('localhost',7556))sock.listen(5)while True:  connection,address = sock.accept()  print "client ip is "  print address  try:    connection.settimeout(5)    buf = connection.recv(1024)    if buf == '1':      connection.send('welcome to python server!')    else:      connection.send('please go out!')  except socket.timeout:    print 'time out'  connection.close()

The client side is as follows:

#!/usr/bin/env pythonimport socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(('localhost',7556))import timetime.sleep(2)sock.send('1')print sock.recv(1024)sock.close()

Remember to close the socket after it is used. [In the above Code, the server forgot to close the socket]
Of course, during the socket connection process, try again t to handle the error.

Note that both the accept and recv functions are blocked. That is to say, they are waiting until a client connects or the latter receives data.

The following is a small FTP example.

Multiple Threads are used to process each request.

Click here to download the sample code.

If the transfer path does not exist, it is created.

I hope this article will help you with Python programming.

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.