Python网络编程(Socket)
2014-04-19 17:17
357 查看
Python网络编程(Socket)
Python提供了两个访问级别的网络服务。在一个较低的水平,您可以访问底层操作系统的基本套接字支持,允许你实现面向连接和无连接协议的客户端和服务器Python有特定的应用程序级的网络协议,如FTP,HTTP等,提供更高级别的访问的库。
本教程为您提供最有名的网络概念的理解 - Socket编程
什么是套接字(Sockets)?
套接字是一个双向的通信信道的端点。套接字可能在沟通过程,进程之间在同一台机器上,或在不同的计算机之间的进程.套接字可以实现通过不同渠道类型的号码:Unix域套接字的TCP,UDP等等。套接字库提供处理处理,共同传输,以及一个通用的接口的具体类.
套接字有自身词汇表:
Term | Description |
---|---|
domain | The 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. |
type | The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols. |
protocol | Typically zero, this may be used to identify a variant of a protocol within a domain and type. |
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 "", 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. |
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. |
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 方法:
Method | Description |
---|---|
s.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 方法:
Method | Description |
---|---|
s.connect() | This method actively initiates TCP server connection. |
一般Socket 方法:
Method | Description |
---|---|
s.recv() | This method receives TCP message |
s.send() | This method transmits TCP message |
s.recvfrom() | This method receives UDP message |
s.sendto() | This method transmits UDP message |
s.close() | This method closes socket |
socket.gethostname() | Returns the hostname. |
一个简单的服务器:
写一个互联网服务器,我们使用的socket模块插座功能可用来创建一个socket对象。一个Socket对象,然后用来调用其他函数来设置套接字服务器.现在调用bind(主机名,端口)函数,给定主机上的一个端口指定为您服务.
接下来,调用的accept方法返回的对象。这种方法等待,直到一个客户端连接到您指定的端口,然后返回一个连接对象,表示客户端的连接.
#!/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
一个简单的客户端:
现在我们将编写一个非常简单的客户端程序,这将打开一个连接到一个特定的端口12345和给定的主机。这是非常简单的创建一个socket客户端使用Python的socket模块功能.socket.connect(主机名或IP, 端口)打开到主机上的TCP端口的连接.
一旦你打开一个套接字,你可以看到它像任何IO对象。当完成后,记得要关闭它,你会关闭文件。
下面的代码是一个非常简单的客户端连接到一个特定的主机和端口,读取从套接字任何可用的数据,然后退出:
#!/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看到的结果.
# 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中的网络/互联网编程的一些重要的模块列表.Protocol | Common function | Port No | Python module |
---|---|---|---|
HTTP | Web pages | 80 | httplib, urllib, xmlrpclib |
NNTP | Usenet news | 119 | nntplib |
FTP | File transfers | 20 | ftplib, urllib |
SMTP | Sending email | 25 | smtplib |
POP3 | Fetching email | 110 | poplib |
IMAP4 | Fetching email | 143 | imaplib |
Telnet | Command lines | 23 | telnetlib |
Gopher | Document transfers | 70 | gopherlib, urllib |
进阶阅读资料:
我已经给你一个Socket编程的快速启动。这是一个大课题,因此建议通过下面的链接去寻找更详细:Unix Socket Programming.
Python Socket Library and Modules.
相关文章推荐
- HTTP协议学习
- ubuntu网络连接图标不显示
- 搜索引擎-网络爬虫
- metasploit中Payload的reverse_tcp和bind_tcp的区别
- 为什么兴趣图谱将重塑我们的社交网络及未来的商业
- 计算机网络 —> 数据链路层
- http://tympanus.net/codrops/ 挺好的前端学习网站
- RTP/RTSP/RTCP 协议详解
- Apache Http Server与Tomcat实现负载均衡和集群
- 中国网络词“no zuo no die”被收入美国俚语词典
- spring学习笔记:spring mvc不得不说的几处配置(转自:http://blog.csdn.net/sunxing007/article/details/4584300)
- C#中HttpWebRequest的GetRequestStream执行的效率太低,甚至偶尔死掉
- 高性能网络编程2--TCP消息的发送
- TCP网络编程--非阻塞accept和非阻塞connect
- XMLHttpRequest
- TCP/IP详解--nagle算法和TCP_NODELAY
- 高性能网络编程--accept建立连接
- 基于Linux下的TCP编程
- Spring MVC 配置 (转自:http://blog.csdn.net/wangdonghua2261/article/details/3872926)
- android检测当前网络是否可用