A very valuable Java code, Socket simulation container, although simple but meaningful

Source: Internet
Author: User
Tags account security

A very valuable Java code, Socket simulation container, although simple but meaningful

What does Tomcat, Weblogic, Jetty, and WebService do? It only listens to a port request on the server through a SOCKET, processes the request, and writes the response information back. Simply put, this is the case. However, in the case of complexity, Tomcat must take into account security, standards, and perfectly compatible with HTTP specifications, multi-thread support, and databases, data Source support, configurability, Web-side management, SSL, and so on are very complicated. The following is an example of code that is very useful for beginners.

package com.ziwen.container;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;public class AppServer {public static void main(String[] args) throws Exception {ServerSocket serverSocket = new ServerSocket(8080);Socket socket =serverSocket.accept();InputStream inputStream  = socket.getInputStream();byte[] msgBytes = new byte[1024];int len = inputStream.read(msgBytes);String msg = new String(msgBytes,0,len);System.out.println(msg);OutputStream outputStream = socket.getOutputStream();PrintWriter printWriter = new PrintWriter(outputStream,true);printWriter.println("successful!");socket.close();serverSocket.close();}}

The following is the HTML code for sending the request:

A useful demo.

In the preceding Java code, a ServerSocket is created to listen to requests from port 8080. The Html code sends an HTML request to the Local Machine (104) through a browser, so that the Java code receives the HTML request and writes the response information back to the browser.
Although this code is very simple, we can release a lot of things, such as JavaScript, image stream, and WebService. On this basis, we can build our own MVC.


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.