Python Socket Programming

Source: Internet
Author: User

Basic Python Socket Module
Python provides two basic socket modules. The first one is the Socket, which provides the standard BSD Sockets API. The second one is
, it provides a server-centric class that simplifies the development of Web servers. Python uses an asynchronous way to do this, and you can provide some plug-in classes to handle application-specific tasks in the server. Table 1 lists the classes and modules that are covered in this section.

Table 1. Python Classes and modules

Low-level network interface (per BSD API)
Provides classes to simplify Web server development
Let's take a look at these modules to understand how they work.
Socket module
The Socket module provides basic network services (also known as BSD APIs) that are familiar to UNIX programmers. This module provides all the features you need to build the socket server and the client.
The difference between this API and the standard C API is that it is object-oriented. In C, the socket descriptor is obtained from the socket call and is then passed as a parameter to the BSD API function. In Python, the socket method returns a socket object to the object that the socket method is applied to. Table 2 shows a few class methods, and table 3 displays some of the instance methods.

Table 2. Class methods for Socket modules

Class method
Low-level network interface (per BSD API)
Socket.socket (family, type)
Creates and returns a new socket object
Converts an IP address string separated by a dot to a full domain name
Socket.gethostbyname (hostname)
Resolves a host name to an IP address string separated by a point number
SOCKET.FROMFD (FD, family, type)
Create a socket object from an existing file descriptor

Table 3. instance method of the Socket module

Instance method
Sock.bind ((ADRs, Port))
Bind the socket to an address and port
Sock.accept ()
Returns a client socket (with client-side address information)
Sock.listen (Backlog)
The socket is set to listen mode, can listen to the backlog external connection request
Sock.connect ((ADRs, Port))
Connect the socket to the defined host and port
SOCK.RECV (buflen[, flags])
Receive data from socket up to Buflen characters
Sock.recvfrom (buflen[, flags])
Receives data from the socket, up to Buflen characters, and returns the remote host and port number of the data source
Sock.send (data[, flags])
Sending data through the socket
Sock.sendto (data[, flags], addr)
Sending data through the socket
Sock.close ()
Close socket
Sock.getsockopt (LVL, optname)
Gets the value of the specified socket option
Sock.setsockopt (LVL, optname, Val)
Sets the value of the specified socket option
The difference between a class method and an instance method is that the instance method needs to have a socket instance (returned from the socket) to execute, and the class method does not need it.
Socketserver Module
The module is a very useful module that simplifies the development of the socket server. The discussion about the use of this module is far beyond the scope of this tutorial, but I'll show you the basic usage, and then you can refer to the links given in the Resources section.
Consider the example given in Listing 2. Here, we implement a simple "Hello World" server, which displays a message when the client connects to it. I first create a request handler, which inherits the
Class. We define a method called handle, which handles requests from the server. Everything that the server does must be handled in the context of the function (and finally, the socket is closed). This process works very simply, but you can use this class to implement a simple HTTP server. In the handle method, we quit with a greeting.
Now that the connection handler is ready, the rest of the work is to create the socket server. We used the
. The TCPServer class and provides the address and port number (on which port to bind the server) and the request processing method. The result is a TCPServer object. Call the Serve_forever method to start the server and make it available for this connection.

Listing 2. Use
Module to implement a simple server

Toggle Line Numbers

Toggle Line Numbers
1 Import Socketserver
3 class Hwrequesthandler (Socketserver.streamrequesthandler):
4 def handle (self):
5 Self.wfile.write ("Hello world!\n")
8 Server = Socketserver.tcpserver (("", 2525), Hwrequesthandler)
9 Server.serve_forever ()
That's it! Python allows any variant of this mechanism, including udpservers and the server that derives the process and thread. See the Resources section for links to more information.

Keyword: python socket
Steps for Python to write server:

The first step is to create the socket object. Call the socket constructor. Such as:
Socket = Socket.socket (family, type)
The family parameter represents the address family, which can be either af_inet or Af_unix. The Af_inet family includes Internet addresses, and the Af_unix family is used for interprocess communication on the same machine.
The type parameter represents a socket type, which can be sock_stream (stream sockets) and Sock_dgram (datagram sockets).

The second step is to bind the socket to the specified address. This is done through the bind method of the Socket object:
Socket.bind (Address)
The socket created by AF_INET, the address must be a two-element tuple in the format (host,port). Host, Port represents the port number. The Bind method throws an Socket.error exception if the port number is in use, the hostname is incorrect, or the port has been persisted.

The third step is to use the Listen method of the socket socket to receive the connection request.
Socket.listen (Backlog)
The backlog specifies the maximum number of clients that are allowed to connect to the server. It has a value of at least 1. When a connection request is received, the requests are queued and the request is rejected if the queue is full.

The fourth step is that the server socket waits for the client to request a connection through the socket's accept method.
Connection, address = socket.accept ()
When the Accept method is called, the socket is in the "Waiting" state. When a client requests a connection, the method establishes the connection and returns the server. The Accept method returns a tuple containing two elements (connection,address). The first element, connection, is the new socket object that the server must communicate with the customer, and the second element address is the customer's Internet location.
The fifth step is the processing phase where the server and the client communicate via the Send and Recv methods (transfer data). The server calls send and sends a message to the customer in string form. The Send method returns the number of characters that have been sent. The server uses the Recv method to receive information from the customer. When calling 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 will be truncated. The excess data will be buffered on the receiving side. When Recv is called later, the extra data is removed from the buffer (and any other data that the customer may have sent since the last call to Recv).
At the end of the transfer, the server calls the socket's Close method to close the connection. Steps for Python to write the client:
Create a socket to connect to the server: socket = socket.socket (family, type)

Connect to the server using the socket's Connect method. For the Af_inet family, the connection format is as follows:
Socket.connect ((Host,port))
Host represents the server host name or ip,port the port number that is bound on behalf of the server process. If the connection succeeds, the client can communicate with the server through the socket, and if the connection fails, a Socket.error exception is thrown.
Processing phase, the client and the server communicate through the Send method and the Recv method.
At the end of the transfer, the client closes the connection by calling the Close method of the socket. Here's a simple example:
Python code

if __name__ = = ' __main__ ':
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sock.bind ((' localhost ', 8001))
Sock.listen (5)
While True:
Connection,address = Sock.accept ()
Connection.settimeout (5)
if buf = = ' 1 ':
Connection.send (' Welcome to server! ')
Connection.send (' Please go out! ')
Except Socket.timeout:
print ' Time Out '
Connection.close ()
Python code

if __name__ = = ' __main__ ':
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sock.connect ((' localhost ', 8001))
Import time
Time.sleep (2)
Sock.send (' 1 ')
Print SOCK.RECV (1024)
Sock.close ()
Running at the terminal and then running will print "Welcome to server!" at the terminal. If you change's Sock.send (' 1 ') to a different value in the terminal will print "Please go out!", Change Time.sleep (2) to a value greater than 5, the server will time out.
Using Python to implement a socket is a simple and easy one, much easier than PHP. Below we use Socketserver
Modules to enable network clients to connect to the server concurrently with non-blocking sockets.
First, let's look at the classes available in the next Socketserver module:
Baseserver: The core functionality of the containing server is linked to the hybrid (Mix-in) class, and this class is used only for derivation, so instances of this class are not generated; Consider using TCPServer and udpserver.
Tcpserver/udpserver: Basic network Synchronization TCP/UDP server.
Unixstreamserver/unixdatagramserver: Basic file-based synchronization tcp/udp server.
Forkingmixin/threadingmixin: The core process or threading function is implemented, and as a hybrid class, it is used with the server class to provide some asynchronous features; This class is not instantiated directly.
Combination of Forkingtcpserver/forkingudpserver:forkingmixin and tcpserver/udpserver.
Baserequesthandler: Contains core functionality for processing service requests. This class is used only for derivation, so instances of this class are not generated to consider using Streamrequesthandler or Datagramrequesthandler.
Streamrequesthandler/datagramrequesthandler: Service Processing tool for TCP/UDP server.
Below we formally enter the topic, here we use Streamrequesthandler and Threadingtcpserver to implement the client and server concurrent connection non-blocking socket.
Threadingtcpserver derives from ThreadingMixIn, which mainly implements the core process of combining threading functionality.
Streamrequesthandler is primarily used for service processing tools for TCP/UDP servers.
First, create the SOCKETSERVERTCP server:
Import Socketserver
From Socketserver import Streamrequesthandler as SRH
From time import CTime

Host = ' '
Port = 3130
Addr = (Host,port)

Class Servers (SRH):
def handle (self):
print ' Got connection from ', self.client_address
Self.wfile.write (' Connection%s:%s at%s succeed! '% (Host,port,ctime ()))
While True:
data = SELF.REQUEST.RECV (1024)
If not data:break
Print data
Self.request.send (data)

print ' server is running .... '
Server = Socketserver.threadingtcpserver (addr,servers)
Server.serve_forever ()
Second, create SOCKETSERVERTCP client
From socket Import *

host = ' localhost '
Port = 3130
BufSize = 1024
Addr = (Host,port)
Client = socket (Af_inet,sock_stream)
Client.connect (addr)

While True:
data = Raw_input ()
If not data or data== ' exit ':
Client.send ('%s\r\n '% data)
data = CLIENT.RECV (bufsize)
If not data:
Print Data.strip ()

Client.close ()
Iii. Executing servers and clients
Server is running ....
Got connection from ('′, 2141)
connection:3130 at Mon Apr 02:44:17 succeed!
Who is U?

Python Socket 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: 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.