详解Python Socket网络编程
Socket是进程间通信的一种方式,它与其他进程间通信的一个主要不同是:它能实现不同主机间的进程间通信,我们网络上各种各样的服务大多都是基于Socket来完成通信的,例如我们每天浏览网页、QQ聊天、收发email等等。要解决网络上两台主机之间的进程通信问题,首先要唯一标识该进程,在TCP/IP网络协议中,就是通过(IP地址,协议,端口号)三元组来标识进程的,解决了进程标识问题,就有了通信的基础了。
本文主要介绍使用Python进行TCPSocket网络编程,假设你已经具有初步的网络知识及Python基本语法知识。
TCP是一种面向连接的传输层协议,TCPSocket是基于一种Client-Server的编程模型,服务端监听客户端的连接请求,一旦建立连接即可以进行传输数据。那么对TCPSocket编程的介绍也分为客户端和服务端:
一、客户端编程
创建socket
首先要创建socket,用Python中socket模块的函数socket就可以完成:
#Socketclientexampleinpython importsocket#forsockets #createanAF_INET,STREAMsocket(TCP) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print'SocketCreated'
函数socket.socket创建一个socket,返回该socket的描述符,将在后面相关函数中使用。该函数带有两个参数:
AddressFamily:可以选择AF_INET(用于Internet进程间通信)或者AF_UNIX(用于同一台机器进程间通信)
Type:套接字类型,可以是SOCKET_STREAM(流式套接字,主要用于TCP协议)或者SOCKET_DGRAM(数据报套接字,主要用于UDP协议)
注:由于本文主要概述一下PythonSocket编程的过程,因此不会对相关函数参数、返回值进行详细介绍,需要了解的可以查看相关手册
错误处理
如果创建socket函数失败,会抛出一个socket.error的异常,需要捕获:
#handlingerrorsinpythonsocketprograms importsocket#forsockets importsys#forexit try: #createanAF_INET,STREAMsocket(TCP) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) exceptsocket.error,msg: print'Failedtocreatesocket.Errorcode:'+str(msg[0])+',Errormessage:'+msg[1] sys.exit(); print'SocketCreated'
那么到目前为止已成功创建了socket,接下来我们将用这个socket来连接某个服务器,就连www.google.com吧。
连接服务器
本文开始也提到了,socket使用(IP地址,协议,端口号)来标识一个进程,那么我们要想和服务器进行通信,就需要知道它的IP地址以及端口号。
获得远程主机的IP地址
Python提供了一个简单的函数socket.gethostbyname来获得远程主机的IP地址:
host='www.google.com' port=80 try: remote_ip=socket.gethostbyname(host) exceptsocket.gaierror: #couldnotresolve print'Hostnamecouldnotberesolved.Exiting' sys.exit() print'Ipaddressof'+host+'is'+remote_ip
现在我们知道了服务器的IP地址,就可以使用连接函数connect连接到该IP的某个特定的端口上了,下面例子连接到80端口上(是HTTP服务的默认端口):
#Connecttoremoteserver s.connect((remote_ip,port)) print'SocketConnectedto'+host+'onip'+remote_ip
运行该程序:
$pythonclient.py Socketcreated Ipofremotehostwww.google.comis173.194.38.145 SocketConnectedtowww.google.comonip173.194.38.145
发送数据
上面说明连接到www.google.com已经成功了,接下面我们可以向服务器发送一些数据,例如发送字符串GET/HTTP/1.1\r\n\r\n,这是一个HTTP请求网页内容的命令。
#Sendsomedatatoremoteserver message="GET/HTTP/1.1\r\n\r\n" try: #Setthewholestring s.sendall(message) exceptsocket.error: #Sendfailed print'Sendfailed' sys.exit() print'Messagesendsuccessfully'
发送完数据之后,客户端还需要接受服务器的响应。
接收数据
函数recv可以用来接收socket的数据:
#Nowreceivedata reply=s.recv(4096) printreply
一起运行的结果如下:
Socketcreated Ipofremotehostwww.google.comis173.194.38.145 SocketConnectedtowww.google.comonip173.194.38.145 Messagesendsuccessfully HTTP/1.1302Found Cache-Control:private Content-Type:text/html;charset=UTF-8 Location:http://www.google.com.sg/?gfe_rd=cr&ei=PlqJVLCREovW8gfF0oG4CQ Content-Length:262 Date:Thu,11Dec201408:47:58GMT Server:GFE/2.0 Alternate-Protocol:80:quic,p=0.02 <HTML><HEAD><metahttp-equiv="content-type"content="text/html;charset=utf-8"> <TITLE>302Moved</TITLE></HEAD><BODY> <H1>302Moved</H1> Thedocumenthasmoved <AHREF="http://www.google.com.sg/?gfe_rd=cr&ei=PlqJVLCREovW8gfF0oG4CQ">here</A>. </BODY></HTML>
关闭socket
当我们不想再次请求服务器数据时,可以将该socket关闭,结束这次通信:
s.close()
小结
上面我们学到了如何:
- 创建socket
- 连接到远程服务器
- 发送数据
- 接收数据
- 关闭socket
当我们打开www.google.com时,浏览器所做的就是这些,知道这些是非常有意义的。在socket中具有这种行为特征的被称为CLIENT,客户端主要是连接远程系统获取数据。
socket中另一种行为称为SERVER,服务器使用socket来接收连接以及提供数据,和客户端正好相反。所以www.google.com是服务器,你的浏览器是客户端,或者更准确地说,www.google.com是HTTP服务器,你的浏览器是HTTP客户端。
那么上面介绍了客户端的编程,现在轮到服务器端如果使用socket了。
二、服务器端编程
服务器端主要做以下工作:
- 打开socket
- 绑定到特定的地址以及端口上
- 监听连接
- 建立连接
- 接收/发送数据
上面已经介绍了如何创建socket了,下面一步是绑定。
绑定socket
函数bind可以用来将socket绑定到特定的地址和端口上,它需要一个sockaddr_in结构作为参数:
importsocket importsys HOST=''#Symbolicnamemeaningallavailableinterfaces PORT=8888#Arbitrarynon-privilegedport s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print'Socketcreated' try: s.bind((HOST,PORT)) exceptsocket.error,msg: print'Bindfailed.ErrorCode:'+str(msg[0])+'Message'+msg[1] sys.exit() print'Socketbindcomplete'
绑定完成之后,接下来就是监听连接了。
监听连接
函数listen可以将socket置于监听模式:
s.listen(10) print'Socketnowlistening'
该函数带有一个参数称为backlog,用来控制连接的个数。如果设为10,那么有10个连接正在等待处理,此时第11个请求过来时将会被拒绝。
接收连接
当有客户端向服务器发送连接请求时,服务器会接收连接:
#waittoacceptaconnection-blockingcall conn,addr=s.accept() #displayclientinformation print'Connectedwith'+addr[0]+':'+str(addr[1])
运行该程序的,输出结果如下:
$pythonserver.py Socketcreated Socketbindcomplete Socketnowlistening
此时,该程序在8888端口上等待请求的到来。不要关掉这个程序,让它一直运行,现在客户端可以通过该端口连接到socket。我们用telnet客户端来测试,打开一个终端,输入telnetlocalhost8888:
$telnetlocalhost8888 Trying127.0.0.1... Connectedtolocalhost. Escapecharacteris'^]'. Connectionclosedbyforeignhost.
这时服务端输出会显示:
$pythonserver.py Socketcreated Socketbindcomplete Socketnowlistening Connectedwith127.0.0.1:59954
我们观察到客户端已经连接上服务器了。在建立连接之后,我们可以用来与客户端进行通信。下面例子演示的是,服务器建立连接之后,接收客户端发送来的数据,并立即将数据发送回去,下面是完整的服务端程序:
importsocket importsys HOST=''#Symbolicnamemeaningallavailableinterfaces PORT=8888#Arbitrarynon-privilegedport s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print'Socketcreated' try: s.bind((HOST,PORT)) exceptsocket.error,msg: print'Bindfailed.ErrorCode:'+str(msg[0])+'Message'+msg[1] sys.exit() print'Socketbindcomplete' s.listen(10) print'Socketnowlistening' #waittoacceptaconnection-blockingcall conn,addr=s.accept() print'Connectedwith'+addr[0]+':'+str(addr[1]) #nowkeeptalkingwiththeclient data=conn.recv(1024) conn.sendall(data) conn.close() s.close()
在一个终端中运行这个程序,打开另一个终端,使用telnet连接服务器,随便输入字符串,你会看到:
$telnetlocalhost8888 Trying127.0.0.1... Connectedtolocalhost. Escapecharacteris'^]'. happy happy Connectionclosedbyforeignhost.
客户端(telnet)接收了服务器的响应。
我们在完成一次响应之后服务器立即断开了连接,而像www.google.com这样的服务器总是一直等待接收连接的。我们需要将上面的服务器程序改造成一直运行,最简单的办法是将accept放到一个循环中,那么就可以一直接收连接了。
保持服务
我们可以将代码改成这样让服务器一直工作:
importsocket importsys HOST=''#Symbolicnamemeaningallavailableinterfaces PORT=5000#Arbitrarynon-privilegedport s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print'Socketcreated' try: s.bind((HOST,PORT)) exceptsocket.error,msg: print'Bindfailed.ErrorCode:'+str(msg[0])+'Message'+msg[1] sys.exit() print'Socketbindcomplete' s.listen(10) print'Socketnowlistening' #nowkeeptalkingwiththeclient while1: #waittoacceptaconnection-blockingcall conn,addr=s.accept() print'Connectedwith'+addr[0]+':'+str(addr[1]) data=conn.recv(1024) reply='OK...'+data ifnotdata: break conn.sendall(reply) conn.close() s.close()
现在在一个终端下运行上面的服务器程序,再开启三个终端,分别用telnet去连接,如果一个终端连接之后不输入数据其他终端是没办法进行连接的,而且每个终端只能服务一次就断开连接。这从代码上也是可以看出来的。
这显然也不是我们想要的,我们希望多个客户端可以随时建立连接,而且每个客户端可以跟服务器进行多次通信,这该怎么修改呢?
处理连接
为了处理每个连接,我们需要将处理的程序与主程序的接收连接分开。一种方法可以使用线程来实现,主服务程序接收连接,创建一个线程来处理该连接的通信,然后服务器回到接收其他连接的逻辑上来。
importsocket importsys fromthreadimport* HOST=''#Symbolicnamemeaningallavailableinterfaces PORT=8888#Arbitrarynon-privilegedport s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print'Socketcreated' #Bindsockettolocalhostandport try: s.bind((HOST,PORT)) exceptsocket.error,msg: print'Bindfailed.ErrorCode:'+str(msg[0])+'Message'+msg[1] sys.exit() print'Socketbindcomplete' #Startlisteningonsocket s.listen(10) print'Socketnowlistening' #Functionforhandlingconnections.Thiswillbeusedtocreatethreads defclientthread(conn): #Sendingmessagetoconnectedclient conn.send('Welcometotheserver.Typesomethingandhitenter\n')#sendonlytakesstring #infiniteloopsothatfunctiondonotterminateandthreaddonotend. whileTrue: #Receivingfromclient data=conn.recv(1024) reply='OK...'+data ifnotdata: break conn.sendall(reply) #cameoutofloop conn.close() #nowkeeptalkingwiththeclient while1: #waittoacceptaconnection-blockingcall conn,addr=s.accept() print'Connectedwith'+addr[0]+':'+str(addr[1]) #startnewthreadtakes1stargumentasafunctionnametoberun,secondisthetupleofargumentstothefunction. start_new_thread(clientthread,(conn,)) s.close()
再次运行上面的程序,打开三个终端来与主服务器建立telnet连接,这时候三个客户端可以随时接入,而且每个客户端可以与主服务器进行多次通信。
telnet终端下可能输出如下:
$telnetlocalhost8888 Trying127.0.0.1... Connectedtolocalhost. Escapecharacteris'^]'. Welcometotheserver.Typesomethingandhitenter hi OK...hi asd OK...asd cv OK...cv
要结束telnet的连接,按下Ctrl-]键,再输入close命令。
服务器终端的输出可能是这样的:
$pythonserver.py Socketcreated Socketbindcomplete Socketnowlistening Connectedwith127.0.0.1:60730 Connectedwith127.0.0.1:60731
到目前为止,我们学习了Python下基本的socket编程,之后还有相关文章向大家介绍,不要走开。