Python Socket Programming Example detailed

Source: Internet
Author: User
Tags bind error handling sleep socket

The example of this article describes the Python socket programming in more detail. Share to everyone for your reference. Specifically as follows:

Copy code code as follows:

Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

The code above creates a socket object. The type parameter represents a socket type and can be sock_stream (stream sockets) and Sock_dgram (datagram sockets). Af_inet represents the type of IP v4 that was created.

Copy code code as follows:

Socket (Address_family,type,protocol_type):

The above three parameters mean:

Address_family indicates which type of socket to build. The most common of course is IP protocol, af_inet. In Unix systems, Af_unix is also more commonly used to establish interprocess communication in UNIX systems.

Type is used to specify the type of communication. It is usually to establish a connection-oriented flow letter. Socket_dgram is a message communication. If the address_family is set to Af_inet, then TCP and UDP are the corresponding.

Protocol is used to specify the protocol type. This parameter is optional. They are usually 0 when establishing TCP or UDP connections. If the first argument is af_inet, then this argument represents the Protocol field in the IP packet.

"UDP is inherently indistinguishable from server and client. All nodes are equivalent.

The second step is to bind the socket to the specified address:

Copy code code as follows:

Sock.bind ((' localhost ', 7556))

The third step is to use the Listen method to listen for requests: "The parameters in the Listen method indicate the maximum number of connections acceptable"

Copy code code as follows:

Sock.listen (5)

The fourth step is to continuously receive requests: When a connection request is received, these requests need to be queued and the request is rejected if the queue is full.

Copy code code as follows:

Connection,address = Sock.accept ()

The Accept method returns a tuple (connection,address) that contains two elements. The first element connection is a new socket object that the server must communicate with the customer, and the second element address is the client's Internet addresses.

The fifth step is the processing phase, in which the server and the client communicate (transmit data) through the Send and recv methods.

If send succeeds, the other buffer already has the data you sent.

#调用recv, the server must specify an integer that corresponds to the maximum amount of data that can be received through this method call. The Recv method enters the "blocked" state when it receives the data, and finally returns a string that represents the received data. If the amount of data sent exceeds the allowable recv, the data is truncated. The extra data will be buffered on the receiving end. When you call recv later, the extra data is removed from the buffer (and any other data that the customer may send since the last call to Recv).

?

1 2 Connection.settimeout (5) buf = CONNECTION.RECV (1024)

The specific processing is as follows:

?

1 2 3 4 if buf = = ' 1 ': connection.send (' Welcome to Python server! ') else:connection.send (' Please go out! ')

Send data to the client using send. 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.

All the code is as follows:

Server End:

?

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 (' out! ') except 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 has been used. "The above code, the server side forgot to close the socket."

Of course, in the socket connection process, it is best to use try except to do the error handling.

Note that both the Accept function and the recv function are blocking. That is, they are waiting until a client connects or the latter has data to receive.

Here is a small example of FTP.

Multithreading is used to process each request.

Sample code Click here to download the site.

Established if the transport path does not exist.

I hope this article will help you with your 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.