Python Network Programming

Source: Internet
Author: User

Python provides two levels of access to network services. :

    • The low-level network service supports the basic socket, which provides the standard BSD Sockets API to access all the methods of the underlying operating system socket interface.

    • The high-level Network Service module, Socketserver, provides a server-centric class that simplifies the development of network servers.

What is a Socket?

A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.

Socket () function

In Python, we use the socket () function to create a socket with the following syntax:

Socket.  Socket([family[, type[, Proto]])        
Parameters
    • Family: The socket family can make Af_unix or af_inet

    • Type: The socket type can be divided into either a connection-oriented or a non-connected SOCK_STREAMSOCK_DGRAM

    • Protocol: General does not fill the default is 0

Socket object (built-in) method
function Description
Server-side sockets
S.bind () The binding address (Host,port) to the socket, under Af_inet, represents the address in the form of a tuple (host,port).
S.listen () Start TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5.
S.accept () Passively accepts TCP client connections, (blocking) waits for a connection to arrive
Client sockets
S.connect () Actively initializing the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection.
S.CONNECT_EX () Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occurs
Socket functions for public use
S.RECV () Receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send () Sends the TCP data to the connected socket by sending the data in the string. The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall () Complete sending of TCP data, complete sending of TCP data. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
S.recvform () The UDP data is received, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
S.sendto () Sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifies the remote address. The return value is the number of bytes sent.
S.close () Close socket
S.getpeername () Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
S.getsockname () Returns the socket's own address. Typically a tuple (ipaddr,port)
S.setsockopt (Level,optname,value) Sets the value of the given socket option.
S.getsockopt (Level,optname[.buflen]) Returns the value of the socket option.
S.settimeout (Timeout) Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ())
S.gettimeout () Returns the value of the current timeout, in seconds, or none if the timeout period is not set.
S.fileno () Returns the file descriptor for the socket.
S.setblocking (flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking mode (the default value). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised.
S.makefile () Create a file associated with the socket
Simple example

We use the socket function of the socket module to create a socket object. The socket object can set up a socket service by calling other functions.

We can now specify Port (port)of the service by invoking the bind (hostname) function.

Next, we call the accept method of the socket object. The method waits for the client to connect and returns a connection object that indicates that the client is connected.

The complete code is as follows:

1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #@Date: 2016-08-02 23:09:464 #@Author: Stlong ([email protected])5 #@Link: [email protected]6 #@Version: $Id $7 8 ImportOS9 ImportSocketTen  Ones =Socket.socket () AHost =Socket.gethostname () -Port = 12345 - S.bind ((host, port)) the  -S.listen (5) -  -  whileTrue: +C, addr =s.accept () -     Print "Connection Address:", addr +C.send ("the information returned by the server! ") AC.close ()

Client

Next we write a simple client instance that connects to the service created above. The port number is 12345.

The socket.connect (hosname, Port) method opens a TCP connection to a service provider that hosts a port of hostname . After the connection we can start from the service end of the data, remember that the operation will need to close the connection after completion.

The complete code is as follows:

1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #@Date: 2016-08-02 23:14:074 #@Author: Stlong ([email protected])5 #@Link: [email protected]6 #@Version: $Id $7 8 ImportOS9 ImportSocketTen  Ones =Socket.socket () AHost =Socket.gethostname () -Port = 12345 -  the S.connect ((host, port)) - PrintS.RECV (1024) -S.close ()

Now we open a terminal, the first terminal executes the server.py file:

$ python server.  PY 

The second terminal executes the client.py file:

$ python client.  
The information returned by the server    ! 

This is when we open the first terminal, we will see the following information output:

Connection address:(' 192.168.0.118 ',62461)    
Python Internet Module

Some important modules for Python network programming are listed below:

Protocol Functional Usefulness Port number Python Module
HTTP Web Access 80 Httplib, Urllib, Xmlrpclib
NNTP Read and post news articles, commonly known as "posts" 119 Nntplib
Ftp File transfer 20 Ftplib, Urllib
Smtp Send mail 25 Smtplib
POP3 Receive mail 110 Poplib
IMAP4 Get Mail 143 Imaplib
Telnet Command line 23 Telnetlib
Gopher Information Lookup 70 Gopherlib, Urllib

More information can be found on the official website of the Python Socket Library and Modules.

Python Network 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.