In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to write your own simple HTTP server with Java, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
HTTP is a big protocol, and a fully functional HTTP server must respond to resource requests and convert URL to the resource name of the local system. Respond to various forms of HTTP requests (GET, POST, etc.). Handle non-existent file requests, return various forms of status codes, parse MIME types, and so on. However, many HTTP servers with specific features do not require all of these features. For example, many websites just want to display "under construction" messages. Obviously, Apache is overqualified for such a site. Such a site can use a custom server that does only one thing. The Java network class library makes it easy to write such a single-task server.
Custom servers are not just for small websites. High-traffic sites such as Yahoo also use custom servers because servers that do only one thing are usually much faster than general-purpose servers. It is easy to optimize a special-purpose server for a task; the result is often much more efficient than a general-purpose server that needs to respond to many requests. For example, for icons and pictures that are repeatedly used in multi-page or high-traffic pages, it is better to use a separate server to process them (and to avoid carrying unnecessary Cookie when requesting, thus reducing request / response data, thereby reducing download bandwidth and increasing speed) The server reads all the image files into memory at startup, providing them directly from RAM, rather than reading them from disk with every request. In addition, if you don't want to record these images separately from the page request that contains them, this separate server will avoid wasting time on logging.
Simple single file server
The function of the server: no matter what request is received, always send the same file. The server is named SingleFileHTTPServer, and the file name, local port, and content encoding are read from the command line. If the default port, the port number is assumed to be 80. If the default encoding, it is assumed to be ASCII.
Import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class SingleFileHTTPServer extends Thread {private byte [] content; private byte [] header; private int port=80; private SingleFileHTTPServer (String data, String encoding, String MIMEType, int port) throws UnsupportedEncodingException {this (data.getBytes (encoding), encoding, MIMEType, port) } public SingleFileHTTPServer (byte [] data, String encoding, String MIMEType, int port) throws UnsupportedEncodingException {this.content=data; this.port=port String header= "HTTP/1.0 200 OK\ r\ n" + "Server: OneFile 1.0\ r\ n" + "Content-length:" + this.content.length+ "\ r\ n" + "Content-type:" + MIMEType+ "\ r\ n\ n"; this.header=header.getBytes ("ASCII") } public void run () {try {ServerSocket server=new ServerSocket (this.port); System.out.println ("Accepting connections on port" + server.getLocalPort ()); System.out.println ("Data to be sent:"); System.out.write (this.content) While (true) {Socket connection=null; try {connection=server.accept (); OutputStream out=new BufferedOutputStream (connection.getOutputStream ()); InputStream in=new BufferedInputStream (connection.getInputStream ()); StringBuffer request=new StringBuffer () While (true) {int c=in.read (); if (cymbals'\ r' | | cymbals'\ n' | | cymbals color 1) {break;} request.append ((char) c) } / / if HTTP/1.0 and future protocols are detected, according to the specification Need to send a MIME header if (request.toString () .indexOf ("HTTP/")! =-1) {out.write (this.header) } out.write (this.content); out.flush () } catch (IOException e) {/ / TODO: handle exception} finally {if (connectionstarting null) {connection.close () }} catch (IOException e) {System.err.println ("Could not start server. Port Occupied ");} public static void main (String [] args) {try {String contentType=" text/plain "; if (args [0] .endsWith (" .html ") | | args [0] .endsWith (" .htm ")) {contentType=" text/html " } InputStream in=new FileInputStream (args [0]); ByteArrayOutputStream out=new ByteArrayOutputStream (); int b; while ((b=in.read ())! =-1) {out.write (b);} byte [] data=out.toByteArray () / / set listening port int port; try {port=Integer.parseInt (args [1]); if (port65535) {port=80;}} catch (Exception e) {port=80 } String encoding= "ASCII"; if (args.length > 2) {encoding=args [2];} Thread t=new SingleFileHTTPServer (data, encoding, contentType, port); t.start () } catch (ArrayIndexOutOfBoundsException e) {System.out.println ("Usage:java SingleFileHTTPServer filename port encoding");} catch (Exception e) {System.err.println (e); / / TODO: handle exception}
The SingleFileHTTPServer class itself is a subclass of Thread. Its run () method handles inbound connections. This server may only provide small files and only support low-throughput web sites. Since all the server needs to do for each connection is to check that the client supports HTTP/1.0 and generate a smaller byte array or two for the connection, this may be sufficient. On the other hand, if you find that the client is rejected, you can use multithreading. Many things depend on the size of the file provided, the number of expected connections per minute, and the threading model of Java on the host. If you play this complex server, there will be obvious benefits from using multithreading.
The Run () method creates a ServerSocket on the specified port. Then it enters an infinite loop, constantly accepting connections and processing connections. When a socket is accepted, the request is read from the client by an InputStream. It checks to see if the * * line contains the string HTTP. If this string is included, the server assumes that the client understands HTTP/1.0 or later, so it sends a MIME header for the file; it then sends the data. If the client request does not contain the string HTTP, the server ignores the header and sends the data directly. The server closes the connection and attempts to accept the next connection.
The main () method simply reads parameters from the command line. Read the file name to be provided from * command line arguments. If no file is specified or the file cannot be opened, an error message is displayed and the program exits. If the file can be read, its contents are read into the byte array data. A reasonable guess will be made about the content type of the file, and the results are stored in the contentType variable. Next, read the port number from the second command line argument. If no port is specified or if the second parameter is not an integer between 0 and 65535, port 80 is used. Read the encoding from the third command line argument (provided). Otherwise, the encoding method is assumed to be ASCII. Then use these values to construct a SingleFileHTTPServer object and start running. This is the only possible interface.
Here are the results of the test:
The command line compiles the code and sets parameters:
Telnet:
First, enable the telnet service (if not, google it yourself), and then test the port of the host:
Result (you can see the output of the request):
HTTP protocol testing:
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.