TCP收发报文

TCP收发报文_第1张图片
Paste_Image.png
#一个简单的接受请求然后传输请求文件的小程序
#!/usr/bin/env python
# coding=utf-8
import socket,sys,time,re,struct,os
import sys
import urllib

HOST="localhost"   #端口
PORT=8888        #主机名
#localhost:8888//C:\Users\wang bei bei\Desktop\1.png
#http://localhost:8888//C:/Users/wang%20bei%20bei/Desktop/1.txt
#文件类型判断jpg/txt->%s 字典映射

class response():
    def __init__(self,str,html):
        self.diction={"txt":"text/plain","jpg":"text/plain","png":"image/png"}
        self.type=str.split(".")[-1]
        self.html=html
        print "html: %s"%self.html
        print "type: %s"%self.type
        print "filename:%s"%str
        with open(str,"rb") as s:
            self.content=s.read()
        print "content:%s"%self.content
    def return_string(self):
        return "%s 200 OK\r\nAccept-Ranges: bytes\r\nContent-Type:%s\r\n\r\n%s"%(self.html,self.diction[self.type],self.content)
listen_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
####################主函数############################
print("Serving HTTP on port %s ..."%PORT)
begin=0
end=0
while True:
    connection,address=listen_socket.accept()
    print address
    connection.settimeout(20)
    while True:
        filename=connection.recv(1024)
        header=filename.split("\r\n")[0]
        filename=header.split()[1]
        filename=filename[2:]
        filename=filename.replace("%20"," ")
        html=header[-9:]
        r=response(filename,html)
        r=r.return_string()
        print "r:%s"%r
        connection.sendall(r)
        break
        print "closing the connection"
        connection.close()

你可能感兴趣的:(TCP收发报文)