Java simple single-file server

Source: Internet
Author: User

The functionality of the server: the same file is always sent regardless of the request received. This 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 method, it is assumed to be ASCII.

The code is:

  1. Import java.io.*;
  2. Import Java.net.ServerSocket;
  3. Import Java.net.Socket;
  4. Public class Singlefilehttpserver extends Thread {
  5. private byte[] content;
  6. private byte[] header;
  7. private int port=80;
  8. private Singlefilehttpserver (string data, string encoding,
  9. String MIMEType, int port) throws Unsupportedencodingexception {
  10. This (data.getbytes (encoding), encoding, MIMEType, port);
  11. }
  12. Public Singlefilehttpserver (byte[] data, string encoding, String MIMEType, int port)throws unsupportedencodingexception {
  13. This.content=data;
  14. This.port=port;
  15. String header="http/1.0 ok\r\n" +
  16. "Server:onefile 1.0\r\n" +
  17. " content-length:" +this.content.length+"\ r \ n" +
  18. " content-type:" +mimetype+"\r\n\r\n";
  19. this.header=header.getbytes ("ASCII");
  20. }
  21. public Void Run () {
  22. try {
  23. ServerSocket server=New ServerSocket (this.port);
  24. System.out.println ("Accepting connections on port" +server.getlocalport ());
  25. System.out.println ("Data to be Sent:");
  26. System.out.write (this.content);
  27. While (true) {
  28. Socket connection=null;
  29. try {
  30. Connection=server.accept ();
  31. OutputStream out=New Bufferedoutputstream (Connection.getoutputstream ());
  32. InputStream in=New Bufferedinputstream (Connection.getinputstream ());
  33. StringBuffer request=New StringBuffer ();
  34. While (true) {
  35. int C=in.read ();
  36. if (c==' \ r ' | | c==' \ n ' | | c==-1) {
  37. Break ;
  38. }
  39. Request.append ((char) c);
  40. }
  41. //If http/1.0 and later protocols are detected, a MIME header will be sent according to the specification
  42. if (request.tostring (). IndexOf ("http/")!=-1) {
  43. Out.write (this.header);
  44. }
  45. Out.write (this.content);
  46. Out.flush ();
  47. } catch (IOException e) {
  48. //Todo:handle exception
  49. }finally{
  50. if (connection!=null) {
  51. Connection.close ();
  52. }
  53. }
  54. }
  55. } catch (IOException e) {
  56. System.err.println ("Could not start server.  Port occupied ");
  57. }
  58. }
  59. public static void Main (string[] args) {
  60. try {
  61. String contenttype="Text/plain";
  62. if (args[0].endswith (". html") | | args[0].endswith (". htm")) {
  63. Contenttype="text/html";
  64. }
  65. InputStream in=New FileInputStream (args[0]);
  66. Bytearrayoutputstream out=New Bytearrayoutputstream ();
  67. int b;
  68. While ((B=in.read ())!=-1) {
  69. Out.write (b);
  70. }
  71. byte[] Data=out.tobytearray ();
  72. //Set the listening port
  73. int port;
  74. try {
  75. Port=integer.parseint (args[1]);
  76. if (port<1| | Port>65535) {
  77. port=80;
  78. }
  79. } catch (Exception e) {
  80. port=80;
  81. }
  82. String encoding="ASCII";
  83. if (args.length>2) {
  84. encoding=args[2];
  85. }
  86. Thread t=New Singlefilehttpserver (data, encoding, ContentType, port);
  87. T.start ();
  88. } catch (ArrayIndexOutOfBoundsException e) {
  89. System.out.println ("Usage:java singlefilehttpserver filename port encoding");
  90. }catch (Exception e) {
  91. System.err.println (e); //Todo:handle exception
  92. }
  93. }
  94. }

The Singlefilehttpserver class itself is a subclass of thread. Its run () method handles inbound connections. This server may only provide small files and support only low-throughput web sites. Since all the work that the server needs to do for each connection is to check whether the client supports http/1.0 and generate one or two smaller byte arrays 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 peak number of connections expected per minute, and the Java threading model on the host. Chess This program complex write server, use multithreading will have obvious benefits.

The Run () method creates a serversocket on the specified port. It then enters an infinite loop, continuously accepting the connection and processing the connection. When a socket is accepted, a request is read from the client by a inputstream. It looks at whether the first row contains string http. If this string is included, the server assumes that the client understands http/1.0 or later, sends a MIME header for the file, and then sends the data. If the client request does not contain string HTTP, the server ignores the header and sends the data directly. The last server closes the connection and attempts to accept the next connection.

The main () method simply reads the parameters from the command line. Reads the file name to be supplied from the first command-line argument. If no file is specified or the file cannot be opened, an error message appears and the program exits. If the file is readable, its contents are read into byte array data. With regard to the content type of the file, a reasonable guess is made and the result is stored in the contenttype variable. Next, read the port number from the second command-line argument. If you do not specify a port or the second parameter is not an integer between 0 and 65535, use port 80. Read the encoding from the third command-line argument (provided). Otherwise, the encoding is assumed to be ASCII. These values are then used to construct a Singlefilehttpserver object that starts running. This is the only possible interface.

Java simple single-file server

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.