Python network programming knowledge, python Network Programming

Source: Internet
Author: User

Python network programming knowledge, python Network Programming
Python Network Programming

Python provides two levels of network services for access. :

  • Low-level network services support basic Sockets. It provides the standard BSD Sockets API and can access all the methods of Socket interfaces of the underlying operating system.
  • SocketServer, a high-level network service module, provides a server center class to simplify the development of network servers.
What is Socket?

Socket, also known as "Socket", usually uses "Socket" to send a request to or respond to a network request, so that processes on a host or computer can communicate with each other.

Socket () function

In Python, we use the socket () function to create a socket. The syntax format is as follows:

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 connection-oriented or non-connection-orientedSOCK_STREAMOrSOCK_DGRAM
  • Protocol: Generally, the default value is 0.
Socket object (built-in) Method
Function Description
Server socket
S. bind () Bind the address (host, port) to the socket. In AF_INET, the address is expressed in the form of a tuple (host, port.
S. listen () Start TCP listening. Backlog specifies the maximum number of connections that the operating system can suspend before a connection is denied. This value must be at least 1, and most applications can be set to 5.
S. accept () Passively accept TCP client connections and wait for the connection to arrive.
Client socket
S. connect () Actively initialize the TCP server connection ,. Generally, the format of address is tuples (hostname, port). If a connection error occurs, the socket. error is returned.
S. connect_ex () Extended version of the connect () function. An error code is returned when an error occurs, instead of throwing an exception.
Common socket Functions
S. recv () Receives TCP data, which is returned as a string. The bufsize specifies the maximum data volume to receive. Flag provides other information about messages, which can be ignored.
S. send () Send TCP data and send the data in string to the connected socket. The returned value is the number of bytes to be sent, which may be smaller than the size of the string.
S. sendall () Send TCP data and send TCP data. Send data in string to the connected socket, but try to send all data before returning. If None is returned successfully, an exception is thrown.
S. recvform () Receives UDP data, similar to recv (), but returns (data, address ). Data is the string containing the received data, and address is the socket address for sending data.
S. sendto () Send UDP data and send the data to the socket. The address is a tuples in the form of (ipaddr, port) and specifies the remote address. The returned value is the number of bytes sent.
S. close () Disable socket
S. getpeername () Returns the remote address of the socket. The returned value is usually a tuples (ipaddr, port ).
S. getsockname () Return the address of the socket. It is usually a tuple (ipaddr, port)
S. setsockopt (level, optname, value) Set the value of the given socket option.
S. getsockopt (level, optname [. buflen]) Return the value of the socket option.
S. settimeout (timeout) Sets the superperiod of socket operations. timeout is a floating point number in seconds. If the value is None, there is no superperiod. Generally, it should be set when the socket is just created during off-peak periods, because they may be used for connection operations (such as connect ())
S. gettimeout () Returns the value of the current superperiod in seconds. If no superperiod is set, None is returned.
S. fileno () Returns the file descriptor of the socket.
S. setblocking (flag) If the flag is 0, the socket is set to non-blocking mode; otherwise, the socket is set to blocking mode (default ). In non-blocking mode, if no data is found when recv () is called, or the send () call cannot send data immediately, a socket. error exception occurs.
S. makefile () Create a file related to the socket
Simple instance Server

We use the socket module'sSocketFunction to create a socket object. A socket object can be used to set a socket service by calling other functions.

Now we can callBind (hostname, port)Function to specifyPort).

Next, we callAcceptMethod. This method waits for the client connection and returnsConnectionObject, indicating that the client has been connected.

The complete code is as follows:

#! /Usr/bin/python #-*-coding: UTF-8-*-# file name: server. pyimport socket # import socket module s = socket. socket () # create a socket object host = socket. gethostname () # obtain the local host name port = 12345 # Set the port s. bind (host, port) # bind port s. listen (5) # Wait for the client to connect while True: c, addr = s. accept () # create a client connection. Print 'Connection address: ', addr c. send (' Welcome To The cainiao tutorial! ') C. close () # close the connection
Client

Next, we will write a simple client instance to connect to the Service created above. The port number is 12345.

Socket. connect (hosname, port)Method To open a TCP connection to the hostHostnameThe port isPortService provider. After the connection, we can start the later data on the server. Remember to close the connection after the operation is complete.

The complete code is as follows:

#! /Usr/bin/python #-*-coding: UTF-8-*-# file name: client. pyimport socket # import socket module s = socket. socket () # create a socket object host = socket. gethostname () # Get the local host name port = 12345 # Set the port s. connect (host, port) print s. recv (1024) s. close ()

Now we open two terminals. The first terminal executes the server. py file:

$ python server.py

The second terminal executes the client. py file:

$ Python client. py welcome to the cainiao tutorial!

This is the first terminal to be opened. The following information is displayed:

Connection address: ('192. 168.0.118 ', 192)
Python Internet Module

The following lists some important Python network programming modules:

Protocol Function usage Port Number Python Module
HTTP Webpage 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 email 25 Smtplib
POP3 Receive email 110 Poplib
IMAP4 Get email 143 Imaplib
Telnet Command Line 23 Telnetlib
Gopher Information Search 70 Gopherlib, urllib

 

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.