python网络编程:一、前言及socket初探
在知乎上看到有人提问,Python 网络编程需要学习哪些网络相关的知识?,看了下,觉得还挺有道理。主要的观点如下:
Python网络编程是一个很大的范畴,个人感觉需要掌握的点有:
- 如何使用Python来创建socket, 如何将socket与指定的IP地址和端口进行绑定,使用socket来发送数据,接受数据,
- 如何使用Python中处理线程,从而编写可以同时处理多个请求的web服务器
- 如何使用Python来控制HTTP层的逻辑,包括如何创建http GET,POST,PUT,DELETE请求,如何处理接受到的HTTP请求,这些分别涉及python的httplib, basehttpserver等模块
- 掌握一种基本的python的web开发框架,比如webpy, django,pylon
- 了解非阻塞式的HTTP Server,比如tornado
- 了解twisted, python编写的消息驱动的网络引擎
参考资料:
网络基础知识
- HTTP: the definitive guide http://www.amazon.com/HTTP-Definitive-Guide-David-Gourley/dp/1565925092/
- Computer Networking: A Top-Down Approach http://www.amazon.com/Computer-Networking-Top-Down-Approach-Edition/dp/0136079679/ref
python 网络编程基础
- python 网络编程 http://www.amazon.com/Foundations-Python-Network-Programming-Goerzen/dp/1590593715
- python socket编程的文档 http://docs.python.org/library/socket.html
- python httplib的文档 http://docs.python.org/library/httplib.html
python常用框架文档:
- django 的官方网站 https://www.djangoproject.com/
- twisted 的官方网站 http://twistedmatrix.com/trac/
- tornado 的官方网站 http://www.tornadoweb.org/
学了一下python的socket
socket概念:
通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。Socket正如其英文原意那样,象一个多孔插座。一台主机犹如布满各种插座的房间,每个插座有一个编号,有的插座提供220伏交流电, 有的提供110伏交流电,有的则提供有线电视节目。 客户软件将插头插到不同编号的插座,就可以得到不同的服务。
主要用到的模块: socket
- 建立新的socket:socket.socket([family[, type[, proto]]])
- 获取远程服务器ip:socket.gethostbyname(host)
- 连接到一个远程套接字地址:socket.connect(address)
- 向socket发送数据:socket.sendall(string[, flags])
- 从socket接受数据:socket.recv(bufsize[, flags])
- Bind the socket to address.: socket.bind(address)
- Listen for connections made to the socket. :socket.listen(backlog)
客户端:
1 # clientsocket.py 2 3 import socket 4 5 def Main(): 6 try: 7 # Address Family : AF_INET (this is IP version 4 or IPv4) 8 # Type : SOCK_STREAM (this means connection oriented TCP protocol) 9 # SOCK_DGRAM indicates the UDP protocol. 10 new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 except socket.error, msg: 12 print 'Failed to creat socket. Error code:', str(msg[0]), 13 print 'Error message:', msg[1] 14 return 15 print 'Socket Created' 16 17 host = 'www.baidu.com' 18 port = 80 19 try: 20 remote_ip = socket.gethostbyname(host) 21 except socket.gaierror: 22 print 'Hostname could not be resolved. Exiting.' 23 return 24 print 'Ip address of', host, 'is', remote_ip 25 26 # Connect to remote server 27 new_socket.connect((host, port)) 28 print 'Socket Connected to', host, 'on ip', remote_ip 29 30 # Send some data to remote server | socket.sendall(string[, flags]) 31 message = 'GET / HTTP/1.1\r\n\r\n' 32 try: 33 new_socket.sendall(message) 34 except socket.error: 35 print 'Send fail.' 36 return 37 print 'Message send successfully.' 38 39 # Receive data | socket.recv(bufsize[, flags]) 40 reply = new_socket.recv(4096) 41 print reply 42 43 # Close the socket 44 new_socket.close() 45 46 47 if __name__ == '__main__': 48 Main()
服务器端:
- Bind the socket to address.: socket.bind(address)
- Listen for connections made to the socket. :socket.listen(backlog)
#! /usr/bin/env python # serversockethand.py """ To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections. """ import socket import thread def Main(): HOST = '' PORT = 8888 new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created.' # Bind socket to local host and port try: new_socket.bind((HOST, PORT)) except socket.error, msg: print 'Bind failed. Error code:', str(msg[0]) + 'Message' + msg[1] return print 'Socket bind complete' # Listening on socket new_socket.listen(10) print 'Socket now listening..' # Now keep talking with client while 1: # Wait to accept a connection conn, addr = new_socket.accept() print 'Connected with', addr[0], ':', str(addr[1]) thread.start_new_thread(clientThread, (conn, )) new_socket.close() # Function for handling connections. This will be used to create threads. def clientThread(conn): # Sending message to connected client conn.send('Welcome to the server. Type something and hit enter\n') while 1: data = conn.recv(1024) if not data: break reply = 'OK..' + data conn.sendall(reply) conn.close() if __name__ == '__main__': Main()