Step-by-Step Tomcat learning Socket

Source: Internet
Author: User

Step-by-Step Tomcat learning Socket

In the previous article, I re-learned the HTTP protocol and deepened my understanding of its working process and principles. So when we access an online resource through a browser, how does the browser send our request to the server where the resource is located, and how can we obtain the server's response to the request. In fact, it uses our common Socket.

Sockets are usually translated into 'sockets '. sockets are the communication endpoints between two machines, and sockets work on TCP/IP protocols. There are two methods for two machines to communicate through Socket. One is error-free TCP, and the other is unordered and error-free UDP.

The TCP mode is generally used in file transmission, because two machines usually need to undergo three-way handshake connection before communication, so the overhead is also relatively large.

UDP is a protocol with errors. The data sent by UDP is unordered and generally used in scenarios such as videos and calls. These scenarios generally do not require data integrity, and some errors can be allowed, as long as the data is continuous to a certain extent.

1. UDP Mode

In JAVA, data is sent through a Socket in UDP mode. The common JAVA APIs are DatagramSocket and DatagramPacket.
DatagramPacket indicates a data packet, which is used to deliver the service without a connection package. Each packet is routed only from one machine to another based on the information contained in the packet. Multiple packages sent from one machine to another may have different routes or may arrive in different order. The package delivery is not guaranteed.

DatagramSocket indicates the socket used to send and receive data packets. A datagram socket is the sending or receiving point of the package delivery service. Each packet sent or received on a datagram socket is independently edited and routed. Multiple packages sent from one machine to another may have different routes or may arrive in different order. Always enable UDP broadcast sending on mongoramsocket.

2. TCP Mode

In JAVA, data is sent and received in TCP mode through Socket. Common JAVA APIs are Socket and ServerSocket. The ServerSocket class implements server sockets. The server socket waits for the request to be transmitted over the network. It performs some operations based on the request and may return results to the requester.

The following two pieces of code show the Socket connection from a single-threaded client to the server.

1) server code
Public static void main (String [] args) {// TODO Auto-generated method stubtry {// create a server Socket to receive data on port 1355. By default, the local ServerSocket server = new ServerSocket (1355); // The accept method will listen on the specified port, and the Socket socket = server will be blocked until the link arrives. accept (); // when there is a link, obtain the SOCKET input stream, used to obtain the data sent from the client BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream (); // gets the output stream of the Socket, used to send data to the client PrintWriter out = new PrintWriter (socket. getOutputStream (); while (true) {String line; // readLine is a blocking method. Before the input data is available, the end of the stream is detected, or an exception is thrown, this method has always blocked line = Br. readLine (); if (line! = Null) {// response data out to the client. println ("server received" + line); out. flush (); // if the client outputs bye, close the link if (line. equals ("bye") break;} socket. close (); // br. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}

2) client code
Public static void main (String [] args) {// TODO Auto-generated method stubtry {// request a link to port 1355 of the Local Machine. When requesting a connection, the server must be started, otherwise, an exception is thrown. Socket socket = new Socket ("127.0.0.1", 1355); // when there is a link, obtain the SOCKET input stream, used to obtain data sent from the server. BufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // gets the output stream of the Socket, used to send data to the server PrintWriter out = new PrintWriter (socket. getOutputStream (); // used to receive the user's console input BufferedReader reader = new BufferedReader (new InputStreamReader (System. in); while (true) {// readLine is a blocking method. Before the input data is available, the stream is detected, or an exception is thrown, this method has been blocking String msg = reader. readLine (); out. flush (); if (msg. equals ("bye") {break;} // print the data returned by the server System. out. println (in. readLine ();} socket. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}

When testing, start the server and then start the client. Then, you can send data to the server through the console of the client and receive the response from the client.

Through the example above, we can summarize the following points:

1) The server starts and waits for client connection requests

2) The client initiates a connection request to the server when necessary (when the task is required ).

3) The server receives the connection request initiated by the customer and receives the data sent by the client. It can process the data as needed and then send the response data to the client.

4) The server does not initiate connection communication.

Through the above points, we can find that this method of work is a common method in J2EE. When we send a request to a site through a browser, the Web server is equivalent to the ServerSocket of the server, and the browser is equivalent to the Socket of the client. The Web server receives the request from the client browser, after processing the request, the browser sends the response data to the browser and then displays the response data.

The following code uses Socket to manually create a Web server to respond to requests from the client browser for static resources on the server. The following code requires a little knowledge about the HTTP protocol.

To test the following code, you can create a new project, either a JAVA project or a Web project.



The httpServer code is as follows:

Public class HttpServer {public static final String WEB_ROOT = System. getProperty ("user. dir ") + File. separator + "webroot"; private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; private boolean shutdown = false; /*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubHttpServer server = new HttpServer (); server. await ();} public void await () {ServerSocket serverSock Et = null; int port = 8080; try {// enable a server SOCKETserverSocket = new ServerSocket (port, 1, InetAddress. getByName ("127.0.0.1");} catch (Exception e) {// TODO: handle has tione. printStackTrace (); System. exit (1);} // If the passed request is not shutdown, call accept and wait for the client browser request while (! Shutdown) {Socket socket = null; InputStream input = null; OutputStream output = null; try {socket = serverSocket. accept (); // receives the request and obtains the input/output stream input = socket. getInputStream (); output = socket. getOutputStream (); Request request = new Request (input); // format the Request, parse the HTTP request header information, and parse the Request URIrequest. parse (); // send response information to the client, and then disable SOCKETResponse Response = new response (output); response. setRequest (request); response. sendStaticResource (); socket. close (); shutdown = request. getUri (). equals (SHUTDOWN_COMMAND);} catch (Exception e) {// TODO: handle has tione. printStackTrace (); continue ;}}}}

The Request Code is as follows:

Public class Request {public Request (InputStream input) {// TODO Auto-generated constructor stubthis. input = input;} private InputStream input; private String uri;/*** return the text between the first two spaces in the HTTP request String. * The first line of the HTTP request is in the format of 'request line', for example, GET/index.html HTTP/1.1 *. Therefore, this method returns the request URI */private String parseUri (String requestString) {int index1, index2; index1 = requestString. indexOf (""); if (index1! =-1) {index2 = requestString. indexOf ("", index1 + 1); if (index2> index1) return requestString. substring (index1 + 1, index2);} return null;}/*** obtain request information from the Socket input stream */public void parse () {StringBuffer request = new StringBuffer (); int I; byte [] buffer = new byte [2048]; try {I = input. read (buffer);} catch (Exception e) {// TODO: handle finished tione. printStackTrace (); I =-1 ;}for (int j = 0; j <I; j ++) {request. append (char) buffer [j]);} uri = parseUri (request. toString ();} public String getUri () {return uri;} public void setUri (String uri) {this. uri = uri ;}}

The Response code is as follows:

Public class Response {private static final int BUFFER_SIZE = 1024; Request request; OutputStream output; public Response (OutputStream output) {this. output = output;} public void setRequest (Request request) {this. request = request;}/*** read a static resource file and respond to the client */public void sendStaticResource () according to the client browser request () throws IOException {byte [] bytes = new byte [BUFFER_SIZE]; FileInputStream FD = null; try {// read the static data in the specified directory according to the request URI File file = new File (HttpServer. WEB_ROOT, request. getUri (); if (file. exists () {fiis = new FileInputStream (file); int ch = fiis. read (bytes, 0, BUFFER_SIZE); while (ch! =-1) {output. write (bytes, 0, ch); ch = FCM. read (bytes, 0, BUFFER_SIZE) ;}} else {// If the resource file does not exist, an error page StringBuffer sb = new StringBuffer (); sb. append ("HTTP/1.1 404 file not found \ r \ n"); sb. append ("Content-Type: text/html \ r \ n"); sb. append ("Content-Length: 23 \ r \ n"); sb. append ("\ r \ n"); sb. append ("

A simple HTML page named hello.html was created for the test. The content is as follows:

<Html> <body> 

Start the HttpServer class before testing. Then, output http: // localhost: 8080/aa.html in the address bar of the browser. Because the aa.html page does not exist, you can see the following response in the browser:


Then enter http: // localhost: 8080/hello.html for testing, as shown below:


We can see that the static resource file hello.html has been successfully written.

Through the above content, you can see the basic working principle of Socket. You can also see how the Web server generally works.
Refer to: in-depth analysis of Tomcat, Baidu...


Previous Article: HTTP protocol for Tomcat's learning process

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.