Python网络编程(Socket)

来源:互联网 发布:手机淘宝自定义链接 编辑:程序博客网 时间:2024/05/17 02:59

Python网络编程(Socket)

Python提供了两个访问级别的网络服务。在一个较低的水平,您可以访问底层操作系统的基本套接字支持,允许你实现面向连接和无连接协议的客户端和服务器
Python有特定的应用程序级的网络协议,如FTP,HTTP等,提供更高级别的访问的库。

本教程为您提供最有名的网络概念的理解 - Socket编程


什么是套接字(Sockets)?

套接字是一个双向的通信信道的端点。套接字可能在沟通过程,进程之间在同一台机器上,或在不同的计算机之间的进程.

套接字可以实现通过不同渠道类型的号码:Unix域套接字的TCP,UDP等等。套接字库提供处理处理,共同传输,以及一个通用的接口的具体类.

套接字有自身词汇表:

TermDescriptiondomainThe family of protocols that will be used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.typeThe type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.protocolTypically zero, this may be used to identify a variant of a protocol within a domain and type.hostnameThe 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 "", 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.
portEach 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.

socket 模块:

要创建一个套接字,你必须使用socket.socket()函数,它在socket模块,其中有一般的语法:

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

下面是参数的描述:

  • socket_family: 这是AF_UNIX或AF_INET,正如我刚才解释.

  • socket_type: 这是SOCK_STREAM,或为SOCK_DGRAM.

  • protocol: 这通常被不用关心,默认为0.

一旦你有套接字对象,那么你可以使用所需的功能来创建你的客户端或服务器程序。以下是所需的功能列表:

服务器 Socket 方法:

MethodDescriptions.bind()This method binds address (hostname, port number pair) to socket.s.listen()This method sets up and start TCP listener.s.accept()This passively accept TCP client connection, waiting until connection arrives (blocking).

客户端Socket 方法:

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

一般Socket 方法:

MethodDescriptions.recv()This method receives TCP messages.send()This method transmits TCP messages.recvfrom()This method receives UDP messages.sendto()This method transmits UDP messages.close()This method closes socketsocket.gethostname()Returns the hostname.

一个简单的服务器:

写一个互联网服务器,我们使用的socket模块插座功能可用来创建一个socket对象。一个Socket对象,然后用来调用其他函数来设置套接字服务器.

现在调用bind(主机名,端口)函数,给定主机上的一个端口指定为您服务.

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

#!/usr/bin/python           # This is server.py fileimport socket               # Import socket modules = socket.socket()         # Create a socket objecthost = socket.gethostname() # Get local machine nameport = 12345                # Reserve a port for your service.s.bind((host, port))        # Bind to the ports.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

一个简单的客户端:

现在我们将编写一个非常简单的客户端程序,这将打开一个连接到一个特定的端口12345和给定的主机。这是非常简单的创建一个socket客户端使用Python的socket模块功能.

socket.connect(主机名或IP, 端口)打开到主机上的TCP端口的连接.

一旦你打开一个套接字,你可以看到它像任何IO对象。当完成后,记得要关闭它,你会关闭文件。
下面的代码是一个非常简单的客户端连接到一个特定的主机和端口,读取从套接字任何可用的数据,然后退出:

#!/usr/bin/python           # This is client.py fileimport socket               # Import socket modules = socket.socket()         # Create a socket objecthost = socket.gethostname() # Get local machine nameport = 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看到的结果.

# Following would start a server in background.$ python server.py & # Once server is started run client as follows:$ python client.py

这将产生以下结果:

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

Python网络模块

可以使用Python中的网络/互联网编程的一些重要的模块列表.

ProtocolCommon functionPort NoPython moduleHTTPWeb pages80httplib, urllib, xmlrpclibNNTPUsenet news119nntplibFTPFile transfers20ftplib, urllibSMTPSending email25smtplibPOP3Fetching email110poplibIMAP4Fetching email143imaplibTelnetCommand lines23telnetlibGopherDocument transfers70gopherlib, urllib

请查看上面提到所有库的合作与FTP,SMTP的POP,IMAP协议.

进阶阅读资料:

我已经给你一个Socket编程的快速启动。这是一个大课题,因此建议通过下面的链接去寻找更详细:

  • Unix Socket Programming.

  • Python Socket Library and Modules.

0 0
原创粉丝点击