Never too old to learn.

http协议自学(3)

Posted on By Andy Zhu

以上我们已经全部完成了静态网页的发布等等

所以接下来我们就要写一种像php一样的东西(虽然远远没有p6p那么辣鸡)

那么我们首先要收到客户端发过来的消息(比如说cookies

所以我们就开始研究cookies

那么废话不多说直接先写一段代码:

uses zul_socket;
var
 server:Tserver;
 b:Vlabel;
 port:Vport;
 procedure responder;
 var
  s,resp:ansistring;
  fin:text;
  ch:char;
 begin
  repeat
   s:=server.recv(b);
  until s<>'';
  writeln(s);
  resp:='HTTP/1.1 200 OK'+#13#10+'Content-Type: text/html'+#13#10#13#10;
  assign(fin,'test.html');
  reset(fin);
  while not eof(fin) do
   begin
    read(fin,ch);
    resp:=resp+ch;
   end;
  close(fin);
  server.send(resp,b);
  server.close(b);
  writeln('connection of ',b,' has ended');
 end;
begin
 port:=8000;
 server:=Tserver.create(port);
 writeln('opened the port of:',port);
 server.init;
 writeln('init success');
 while true do
  begin
   b:=server.accept;
   writeln('connected:',b);
   responder;
  end;
end.

这次我们写的服务端不能像上次那样只有一个显示客户端发过来的消息的功能了

这次的服务端还应该懂那么一点点的http语法

test.html:

<html>
    <head>
        <title>test</title>
        <meta charset="utf-8">
    </head>
    <body>
        <script>
            document.cookie="testhead=testvalue"
            document.cookie="test1=test2";
        </script>
    </body>
</html>

然后浏览器中打开这个网页,我们就看见了cookies中的两个内容:

testheadtestvalue

test1test2

在服务端中的内容

GET /favicon.ico HTTP/1.1
Host: localhost:8000
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
Accept: image/webp,image/apng,image/*,*/*;q=0.8
Referer: http://localhost:8000/
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: testhead=testvalue; test1=test2



OK

然后再来了解一下cookies的存在时长:

如果就像上文那样设置,那么一旦会话结束,cookies自动消失,所以再次连接的时候要第二次握手才会把cookies传过来

如果设置了存在时间,那么在第一次握手的时候就会把cookies传过来

然后我们就又可以通过客户端发来消息的格式了解一下服务端远程设置cookies的语法(话说其实不要也可以)