Python socket programming example

Source: Internet
Author: User

Python socket programming example

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

Copy the Code 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 the Code 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 the Code 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 the Code 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 the Code 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 ).

?

1

2

Connection. settimeout (5)

Buf = connection. recv (1024)

The procedure is as follows:

?

1

2

3

4

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.

?

1

2

3

4

5

6

7

8

Import socket

Sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)

Sock. connect ("localhost", 7556 ))

Import time

Time. sleep (2)

Sock. send ('1 ')

Print sock. recv (1024)

Sock. close ()

This is the entire communication process.

The Code is as follows:

Server:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#! /Usr/bin/env python

Import socket

Sock = 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! ')

Failed t socket. timeout:

Print 'time out'

Connection. close ()

The client side is as follows:

?

1

2

3

4

5

6

7

8

9

#! /Usr/bin/env python

Import socket

Sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)

Sock. connect ("localhost", 7556 ))

Import time

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

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.