设为首页 收藏本站
查看: 1134|回复: 0

[经验分享] python网络编程:一、前言及socket初探

[复制链接]

尚未签到

发表于 2015-4-27 09:26:28 | 显示全部楼层 |阅读模式
在知乎上看到有人提问,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)




以下代码主要参考这个教程:http://www.binarytides.com/python-socket-programming-tutorial/

客户端:

http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/Users/Administrator/AppData/Local/youdao/ynote/images/9135BFCE02C24F3EB73DDE2FD3FFD680/client.png




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()
  


http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/Users/Administrator/AppData/Local/youdao/ynote/images/2EABE3D35EEC42F78672CACFAA79B92D/ser.png

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-61037-1-1.html 上篇帖子: Python 十进制转二进制 下篇帖子: python format string (转)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表