Python Network Programming 简明教程

Python - Sockets Programming

Python 提供 two 层对网络服务的访问权限。在较低层,您可以在底层操作系统中访问基本套接字支持,这允许您为面向连接和无连接协议实现客户端和服务器。

Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.

Python 还具有库,提供对特定应用程序级网络协议的更高级访问,例如 FTP、HTTP 等。

Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.

套接字是双向通信通道的端点。套接字可以在进程中、位于同一计算机上的进程之间或位于不同大陆上的进程之间通信。我们在 Python 中使用 socket 模块创建和使用套接字。

Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. We use the socket module in python to create and use sockets.

套接字具有自己的词汇:

Sockets have their own vocabulary −

Sr.No.

Term & Description

1

Domain The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

2

type The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.

3

protocol Typically zero, this may be used to identify a variant of a protocol within a domain and type.

4

hostname The identifier of a network interface − A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation A string "<broadcast>", which specifies an INADDR_BROADCAST address. A zero-length string, which specifies INADDR_ANY, or An Integer, interpreted as a binary address in host byte order.

5

port Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.

The socket Module

要创建套接字,您必须使用 socket 模块中提供的 socket.socket() 函数,其一般语法为 −

To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax −

s = socket.socket (socket_family, socket_type, protocol=0)

以下是参数说明 −

Here is the description of the parameters −

  1. socket_family − This is either AF_UNIX or AF_INET, as explained earlier.

  2. socket_type − This is either SOCK_STREAM or SOCK_DGRAM.

  3. protocol − This is usually left out, defaulting to 0.

一旦有了套接字对象,就可以使用所需函数创建您的客户端或服务器程序。

Once you have socket object, then you can use required functions to create your client or server program.

Server Socket Methods

Sr.No.

Method & Description

1

s.bind() This method binds address (hostname, port number pair) to socket.

2

s.listen() This method sets up and start TCP listener.

3

s.accept() This passively accept TCP client connection, waiting until connection arrives (blocking).

Client Socket Methods

Sr.No.

Method & Description

1

s.connect() This method actively initiates TCP server connection.

General Socket Methods

Sr.No.

Method & Description

1

s.recv() This method receives TCP message

2

s.send() This method transmits TCP message

3

s.recvfrom() This method receives UDP message

4

s.sendto() This method transmits UDP message

5

s.close() This method closes socket

6

socket.gethostname() Returns the hostname.

A Simple Server

要编写 Internet 服务器,我们使用 socket 模块中提供的 socket 函数来创建套接字对象。然后使用套接字对象调用其他函数来设置套接字服务器。

To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.

现在调用 bind(hostname, port) 函数,为在给定主机上的服务指定端口。

Now call bind(hostname, port) function to specify a port for your service on the given host.

接下来,调用返回对象的 accept 方法。此方法会一直等待直到某个客户端连接到您指定的端口,然后返回表示对该客户端连接的连接对象。

Next, call the accept method of the returned object. This method waits until a client connects to the port you specified, and then returns a connection object that represents the connection to that client.

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

A Simple Client

让我们编写一个非常简单的客户端程序,它打开到给定端口 12345 及给定主机的连接。这非常简单,只需使用 Python 的套接字模块函数来创建一个套接字客户端。

Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python’s socket module function.

socket.connect(hosname, port ) 打开到端口上主机名的 TCP 连接。一旦获得打开的套接字,你就可以像读取任何 IO 对象一样从中读取。完成后,请记住关闭它,就像关闭文件一样。

The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.

以下代码是一个非常简单的客户端,它连接到给定的主机和端口,从套接字读取任何可用数据,然后退出 −

The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits −

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

现在,在后台运行此 server.py,然后运行上面的 client.py 便可以看到结果。

Now run this server.py in background and then run above client.py to see the result.

# Following would start a server in background.
$ python server.py &

# Once server is started run client as follows:
$ python client.py

它将产生以下结果 −

This would produce following result −

Got connection from ('127.0.0.1', 48437)
Thank you for connecting

Socket with Public URL

在下面的示例中,我们使用了套接字模块中的几个方法来查找服务器和主机名的地址信息。

In the below example we use few methods from the socket module to find the address information of server and host name details.

import socket
from pprint import pprint

# get server address
addrinfo = socket.getaddrinfo('tutorialspoint.com', 'www')

pprint(addrinfo)

# get server hostname
print socket.gethostname()

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

[(2, 1, 0, '', ('94.130.81.180', 80))]
DESKTOP-JXYKQCPLP