Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement java Server

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will give you a detailed explanation on how to implement the java server. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. HTTP

Http request

Generally, a http request consists of the following three parts:

1 request method, such as get,post

2 request header

3 entity

An example of a http request is as follows:

GET / index.jsp HTTP/1.1

Host: localhost:8080

User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: keep-alive

Pay attention to the url in the red part, which we will intercept later.

Http response

Similar to the http request, the http response consists of three parts

1 protocol-status code-description

2 response head

3 response entity segment

Two socket classes

A socket is the breakpoint of a network connection. Sockets enable applications to read data from the network and write data to it. Applications on different computers can send or accept byte streams through sockets. The Socket class is provided in java to implement this function, and the input and output streams in the network can be obtained through getInputStream and getOutputStream.

However, the Socket class alone cannot achieve the function of building a server application, because the server must always be on standby, so the ServerSocket class is provided in java to handle requests waiting from the client. When ServerSocket receives the request from the client, it creates an instance to handle communication with the client.

Implementation of three server applications

First, we need to build a class requst that encapsulates the request information, a class response that responds to the request, and a main program httpServer to handle the request from the client.

Package com.lwq;import java.io.IOException;import java.io.InputStream;/** * @ author Joker * Class description * convert the request information sent by the browser into characters and intercept url * / public class Request {/ / input stream private InputStream input; / / intercept url, such as http://localhost:8080/index.html, and intercept / index.html private String uri; public Request (InputStream inputStream) {this.input = inputStream } public InputStream getInput () {return input;} public void setInput (InputStream input) {this.input = input;} public String getUri () {return uri;} public void setUri (String uri) {this.uri = uri } / / read character information from sockets public void parse () {StringBuffer request = new StringBuffer (2048); int I = 0; byte [] buffer = new byte [2048]; try {I = input.read (buffer) } catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace (); I =-1;} for (int j = 0polijindex1) {return requestString.substring (index1+1,index2);}} return null;}}

The following is the class response that encapsulates the response request:

Package com.lwq;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.OutputStream;import java.io.PrintWriter;/** * @ author Joker * @ version creation time: Sep 5, 2012 9:59:53 PM * Class description returns the result according to the corresponding information * / public class Response {private static final int BUFFER_SIZE = 1024; Request request; OutputStream output Public Response (OutputStream output) {this.output = output;} public void sendStaticResource () throws IOException {byte [] bytes = new byte [buff _ SIZE]; FileInputStream fis = null; File file = new File (HttpServer.WEB_ROOT,request.getUri ()); if (file.exists ()) {try {fis = new FileInputStream (file) Int ch = fis.read (bytes,0,BUFFER_SIZE); while (ch! =-1) {output.write (bytes,0,ch); ch = fis.read (bytes,0,BUFFER_SIZE) } catch (FileNotFoundException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} finally {if (fis! = null) {fis.close () } else {/ / cannot find the file String errorMessage = "HTTP/1.1 404 File Not Found\ r\ n" + "Content-Type: text/html\ r\ n" + "Content-Length: 23\ r\ n" + "\ r\ n" + "File Not Found" Try {output.write (errorMessage.getBytes ()); output.flush ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} public Request getRequest () {return request } public void setRequest (Request request) {this.request = request;} public OutputStream getOutput () {return output;} public void setOutput (OutputStream output) {this.output = output;} public static int getBUFFER_SIZE () {return BUFFER_SIZE;}}

Next comes the main program.

The package com.lwq;import java.io.File;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;/** * @ author Joker * class states that * / public class HttpServer {/ * @ param args * / / WEB_ROOT is the root directory of the server public static final String WEB_ROOT = System.getProperty ("user.dir") + File.separator+ "webroot" / / closed command private static final String SHUTDOWN_COMMAND= "/ SHUTDOWN"; public static void main (String [] args) {/ / TODO Auto-generated method stub HttpServer server = new HttpServer (); server.await ();} public void await () {ServerSocket serverSocket = null; int port = 8080 Try {serverSocket = new ServerSocket (port,1,InetAddress.getByName ("127.0.0.1")); while (true) {try {Socket socket = null; InputStream input = null; OutputStream output = serverSocket.accept (); input = socket.getInputStream () Output = socket.getOutputStream (); / / encapsulate the request request Request request = new Request (input); request.parse (); / / encapsulate the response object Response response = new Response (output); response.setRequest (request); response.sendStaticResource (); socket.close () } catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace (); continue;}} catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace () }}}

Run httpServer and type http://localhost:8080/index.jsp, in the browser to see the result of the server's response.

This is the end of this article on "how to implement a java server". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report