多手段输出系统时间(Node,Ruby,Python,Java,C#,PhP)

此为初学者为了学习 HTTP 而记。

下面从Node.js开始,依次到Ruby,Python,Java,C#,最后到PhP。通过直接给出代码,以直观地观察各类奇技淫巧。

Node.js:

#!/usr/bin/env node

const http = require('http')

http.createServer((req, res) => {
  res.writeHeader(200, {
    'Content-Type': 'text/html; charset=UTF-8',
  })
  res.end(`Current Time(GMT): ${ Date() }`)
}).listen(3000)

Ruby有一个核心http库,名为webrick,用起来简单有效:

#!/usr/bin/ruby

require "webrick"

class MyServlet < WEBrick::HTTPServlet::AbstractServlet
  def do_GET(request, response)
    response.status = 200
    response.content_type = 'text/plain; charset=UTF-8'
    response.body = Time.now.to_s
  end
end

server = WEBrick::HTTPServer.new(:Port => 1234)
server.mount '/', MyServlet
trap('INT') { server.shutdown }
server.start

上面看得出来,Node描述起来是很简洁的。ruby使用webrick的HTTPServlet::AbstractServlet类来处理,然后输出当前时间。

然后Python,与webrick异曲同工,Python http-BaseHTTPRequestHandler输出系统时间:

#!/usr/bin/env python3

import http.server
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler

from time import strftime, localtime, time

class DateHttpRequestHandler(BaseHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    self.send_header('Content-type', 'text/plain; charset=UTF-8')
    self.end_headers()
    self.wfile.write(bytes('Current time: {0}'.format(
      strftime('%Y-%m-%d %H:%M:%S',  localtime(time()))
    ), 'utf-8'))

def run(server_class = HTTPServer, handler_class = DateHttpRequestHandler):
  server_address = ('', 4000)
  httpd = server_class(server_address, handler_class)
  httpd.serve_forever()

if __name__ == '__main__':
  run()

Java:

import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

import java.util.Date;
import java.text.SimpleDateFormat;

class TimeServer {

  public static void main(String[] args) {
    TimeServer server = new TimeServer();
    server.await();
  }

  private void logHeader(InputStream input) {
    // log request header
    StringBuffer request = new StringBuffer(2048);
    byte[] buffer = new byte[2048];
    int i;
    try {
      i = input.read(buffer);
    } catch (Exception e) {
      e.printStackTrace();
      i = -1;
    }

    for (int j = 0; j < i; j++) {
      request.append((char) buffer[j]);
    }

    System.out.println(request.toString());
  }

  private void sendHeaderAndBody(OutputStream output) {
    // date
    Date date = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // http header and body
    String okMessage = "" +
      "HTTP/1.1 200 OKn" +
      "Content-Type: text/html; charset=utf-8n" +
      "Server: Java SE 1.8n" +
      "Connection: keep-aliven" +
      "n" +
      "
Current time: " + df.format(date) + "
"; try { output.write(okMessage.getBytes()); } catch (Exception e) { e.printStackTrace(); } } public void await() { ServerSocket serverSocket = null; int port = 8080; try { serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); System.exit(1); } // Loop waiting for a request while (true) { // http socket Socket socket = null; InputStream input = null; OutputStream output = null; try { socket = serverSocket.accept(); input = socket.getInputStream(); output = socket.getOutputStream(); logHeader(input); sendHeaderAndBody(output); // Close the socket socket.close(); } catch (Exception e) { e.printStackTrace(); continue; } } } }

C#:

转载自:https://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server

WebServer

using System;
using System.Net;
using System.Threading;
using System.Text;

namespace SimpleWebServer
{
    public class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, string> _responderMethod;

        public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
        {
            if (!HttpListener.IsSupported)
                throw new NotSupportedException(
                    "Needs Windows XP SP2, Server 2003 or later.");

            // URI prefixes are required, for example 
            // "http://localhost:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");

            // A responder method is required
            if (method == null)
                throw new ArgumentException("method");

            foreach (string s in prefixes)
                _listener.Prefixes.Add(s);

            _responderMethod = method;
            _listener.Start();
        }

        public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
            : this(prefixes, method) { }

        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Console.WriteLine("Webserver running...");
                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                string rstr = _responderMethod(ctx.Request);
                                byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                            }
                            catch { } // suppress any exceptions
                            finally
                            {
                                // always close the stream
                                ctx.Response.OutputStream.Close();
                            }
                        }, _listener.GetContext());
                    }
                }
                catch { } // suppress any exceptions
            });
        }

        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }
    }
}

main

using System;
using System.Net;

namespace SimpleWebServer
{
    class Program
    {
        static void Main(string[] args)
        {
            WebServer ws = new WebServer(SendResponse, "http://localhost:8080/");
            ws.Run();
            Console.WriteLine("A simple webserver. Press a key to quit.");
            Console.ReadKey();
            ws.Stop();
        }

        public static string SendResponse(HttpListenerRequest request)
        {
            return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
        }
    }
}

PhP:

<? echo 'Current Time: ' . Date('Y-m-d H:i:s') ?>

上面列的很直观。

参考:

  1. https://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s