python第四天

浏览器与Server交互:

import socket

def handle_request(client):
buf = client.recv(1024)
client.send('HTTP/1.1 200 OK\r\n\r\n')


def main():
#创建socket对象
socketServer = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#监听端口
socketServer.bind(('127.0.0.1',8001))
#开始监听
socketServer.listen(5)

while True:
#阻塞,deng...
#直到有请求连接
print '.'*30
connection,address = socketServer.accept()
#connection,代表客户端socket对象
#address,客户端地址
#handle_request(connection)
buf = connection.recv(1024)
print buf
connection.send('HTTP/1.1 200 OK\r\n\r\n')
connection.send('Hello World')
connection.close()

if __name__ == '__main__':
main()

Client与Server交互:
Client端:
import socket

socket_client = socket.socket()
socket_client.connect(('127.0.0.1',8009))
socket_client.settimeout(5)

while True:
inp = raw_input('please input:')
socket_client.sendall(inp)
res_size = socket_client.recv(1024)
print 'going to recv data size:',res_size,type(res_size)
total_size = int(res_size)
receive_size = 0
while True:
data = socket_client.recv(1024)
receive_size+=len(data)
print '---data---'
if total_size == receive_size:
print data
print '---not data---'
break
print data
if inp == 'exit':
break
socket_client.close()

单线程Server:
import socket

socketServer = socket.socket()
socketServer.bind(('localhost',8341))
socketServer.listen(5)
while True:
print 'waiting...'
conn,addr = socketServer.accept()
#最多接受size
client_data = buf = conn.recv(1024)
print client_data
conn.send('wo shi fu wu duan')
conn.close()

多线程Server:
import SocketServer
import os


class MyServer(SocketServer.BaseRequestHandler):
def handle(self):
# print self.request,self.client_address,self.server
# conn = self.request #每一个客户端
print 'get connection from',self.client_address
while True:
data = self.request.recv(1024)
print "Recv from [%s] cmd :%s"%(self.client_address,data)
cmd_res = os.popen(data).read()
self.request.send(str(len(cmd_res)))
self.request.sendall(cmd_res)

if __name__ == '__main__':
server = SocketServer.ThreadingTCPServer(('127.0.0.1',8009),MyServer)
server.serve_forever()
 





posted @ 2016-12-08 09:41  菜鸟,你好  阅读(172)  评论(0编辑  收藏  举报