python-网络编程-03
首先我们可以看下可以最简单的交互性的服务端和客户端程序
server
import socket def main(): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind(('localhost',8000)) sock.listen(5) while True: print '1' connection ,clent_addr = sock.accept() while 1: buf = connection.recv(1024) connection.sendall('hi') print buf connection.close() if __name__ == '__main__': main()
[server]:在创建socket之后,服务端会一直保持阻塞状态,然后一旦有用户连接,就立即等待用户发送数据,然后接收到用户发的数据之后 理解返回一个字符后,然后状态变成等待下次连接
client
import socket sock = socket.socket() sock.connect(('localhost', 8000)) sock.settimeout(5) while 1: res = sock.recv(1024) print res data = raw_input('input:') sock.sendall(data) sock.close()
[client]:去连接server端然后不断发送数据,然后接受返回。
-------------------------------------------------------------------------------
那么你可以发现上面的server端的代码 其实只能同时接受一个请求,因为只有一个线程去处理这个段代码
那么我可以吧server端的代码换成
import SocketServer class MyServer(SocketServer.BaseRequestHandler,object): def handle(self): conn = self.request conn.sendall('this is a tast') Flag = True while Flag: data = conn.recv(1024) print "data:",data if data == "exit": Flag = True elif data == '0': conn.sendall("The winter in comming") else: conn.sendall("please input again") if __name__ == "__main__": server01 = SocketServer.ThreadingTCPServer(('127.0.0.1',8080),MyServer) print "server is running.." server01.serve_forever()
我们通过借助socket自带的类写出来了 多线程的服务器端,能够收发消息
那么我们可以在这个代码的基础上修改,能够发送命令,返回命令
[server]
import SocketServer,os class MyServer(SocketServer.BaseRequestHandler,object): def handle(self): conn = self.request Flag = True while Flag: data = conn.recv(1024) res = os.popen(data).read() res_length=len(res) conn.send(str(res_length)) msg_num = conn.recv(1024) if msg_num == "10012": print len(res),"-->len" print "data:",data conn.sendall(res) if __name__ == "__main__": server01 = SocketServer.ThreadingTCPServer(('127.0.0.1',8040),MyServer) print "server is running.." server01.serve_forever()
[client]
import socket sock = socket.socket() sock.connect(('localhost', 8040)) sock.settimeout(5) while 1: data = raw_input('input:') sock.sendall(data) res_length = int(sock.recv(1024)) sock.send("10012") print 'length:',res_length while True: if res_length <= 0: break res = sock.recv(1024) print res res_length -= 1024 sock.close()
这里需要注意的是
1:因为服务端 不知道能发送多大的数据,那么在接收数据之前我们需要,先验证一下数据长度,然后根据长度,来决定如何收取