Java Xiaobai Learning Guide [day30]---Web Basics-Network Programming&Http Protocol&Custom Web Server

1. Computer network programming

1. Why learn network programming

​ ① Write html files on the local disk, which can be opened and accessed through a browser;

​ ②, visit other people's software/file/website -> protocol + address (ip) + port

​ ③, open the web server

2. Awareness of the Internet

The network is divided into: local area network, wide area network (World Wide Web)

IP: ip is a unique identifier under the same network; it can be checked under DOS window ipconfig; at the same time ping 域名, the ip corresponding to this domain name can be checked under DOS .

Classification of IP:

Category A: left to government agencies

Category B: Medium-sized companies

Category C: Anyone who needs it

Class D: used for multicast

Type E: for experiment

Insert picture description here

Currently ipv4 is mainly used, ipv6 is in the experimental stage, and some experimental institutions are using it, 128 bits, divided into 8 segments, hexadecimal values ​​from 0000 to FFFF.

The way to get ip in java: InetAddress

@Test
	public void testGetIP() throws Exception {
    
    
		// 返回本地主机名与IP。
		InetAddress localHost = InetAddress.getLocalHost();
		System.out.println(localHost);
		// 返回本地主机名与IP。
		InetAddress byName = localHost.getByName("LAPTOP-QJN7NLRN");
		System.out.println(byName);
		//仅获取当前InetAddress对象的ip
		System.out.println(localHost.getHostAddress());
		//获取淘宝的ip信息
		InetAddress byName2 = InetAddress.getByName("taobao.com");
		System.out.println(byName2);
		System.out.println("淘宝网的ip是:"+byName2.getHostAddress());
	}

3. Port

Port numbers are used to distinguish different applications. Two programs on the same computer cannot use the same port, and conflicts will occur. The port number range on the computer is 0-65535, of which 0-1023 are reserved by the system.

To access a computer, if you do not enter the port number, port 80 will be found by default.

mysql port number: 3306

tomcat port number: 8080

4, URL sum URI

URL: Uniform Resource Locator (protocol://ip:port/resource path)

Example: http://127.0.0.1:8080/class_info/java_jichu.html

URI: Uniform Resource Path

/class_info/java_jichu.html

Exercise: Crawl the information of a website, through the URL tool

Ideas:

①. First obtain the URL object through the address and find the website

② Get the input stream and read web page information

③. Create an output stream, use a file output stream, and write directly into the file

④. Write the content of the input stream to the output stream. This is to guide the commons-io package, using the copy method in IOUtils

⑤, Guanliu

	//获取网站需要用到URL类:
		URL url = new URL("https://douban.com/");
		//获取输入流
		InputStream in = url.openStream();
		//创建接收的文件输出流,作为抓取后的文件输出存放
		FileOutputStream out = new FileOutputStream("文件存放地址.html");
		//传递到输出流中
		IOUtils.copy(in, out);
		//关流
		out.close();
		in.close();
	}

5. UDP and TCP

Both are transport layer protocols, and network communication is done through them.

TCP: Reliable transmission protocol, low performance, multi-use, upload and download and other functions that need to consider security (three handshake, four wave of hands)

UDP: Unreliable transmission protocol, high performance, easy to lose packets by then, so it is mostly used for games, chats, etc.

6. Socket programming

Socket is a protocol, which is translated as socket (socket is the endpoint of communication between two machines), socket programming is supported in java, and Socket (implementation of client socket) and SeverSocker (implementation service) are provided. End socket)

Ideas:

Insert picture description here

Server-side code


public class ServerTest {
    
    
	// 先定义serversocket对象
	private ServerSocket ss = null;

	// 创建构造器,在创建服务器端对象的时候,要将服务器端启动
	public ServerTest() throws Exception {
    
    
		System.out.println("服务器已经准备就绪");
		// 给定一个端口号,作为监听对象,只要有人调用这个端口,就是需要启动服务器
		ss = new ServerSocket(8989);
		System.out.println("服务端已上线");
	}

	// 创建服务器
	public void start() throws Exception {
    
    
		// 需要一直处于等待状态,等待客户端,同时获取socket对象
		Socket socket = ss.accept();
		// 因为数据存在socket中,需要从中获取输入流
		InputStream in = socket.getInputStream();
		// 将输入流进行包装,方便读取,包装进reader
		InputStreamReader is = new InputStreamReader(in,"UTF-8");
		// 再包装进BufferedRader,可以读取一行
		BufferedReader bufferedReader = new BufferedReader(is);
		// 现在可以按行读取数据
		String str = bufferedReader.readLine();
		// 打印从客户端获取的内容
		System.out.println(str);
	}

	// 需要main方法把客户端运行起来
	public static void main(String[] args) throws Exception {
    
    
		ServerTest se = new ServerTest();
		se.start();
	}
}

Client code


public class ClientTest {
    
    
	//先声明客户端socket
	private Socket so = null;
	//创建构造器,在创建客户对象的时候,客户端就要启动
	public ClientTest() throws Exception{
    
    
		//需要传入两个参数,分别是IP,和端口号
		so = new Socket("127.0.0.1",8989);
	}
	//客户端执行功能
	public void start() throws Exception{
    
    
		//首先从socket中拿到输出流
		OutputStream out = so.getOutputStream();
		//包装进writer方便输出
		OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
		//这里有两种方式,可以直接输出(注意换行,因为服务端是按行读取),然后刷新flush,就可以输出了;
		//也可以再次进行包装,包装进PrintWriter【打印流】,要注意第二个参数是是否自动刷新
		PrintWriter printWriter = new PrintWriter(writer,true);
		//可以输出换行加刷新
		printWriter.println("嗨!你听到了吗!我再叫你!");
	}
	//需要main方法将客户端运行起来
	public static void main(String[] args) throws Exception {
    
    
		ClientTest client = new ClientTest();
		client.start();
	}
}

Two, HTTP protocol

The TCP/IP protocol is a transport layer protocol, which mainly solves how to transmit data in the network, while HTTP is an application layer protocol, which mainly solves how to package data. (Achieve cross-server browser)

Note: The browser sends data to the server as a request. The server feedback data to the browser is a response (response);

Insert picture description here

1. Request header

Insert picture description here

2. Response header

Insert picture description here

3. Common response codes

200: processed successfully

404: The requested resource cannot be found

500: The server code is abnormal

Three, custom web server


public class Webserver {
    
    
	private ServerSocket ss = null;

	public Webserver() throws Exception {
    
    
		ss = new ServerSocket(8888);
	}

	public void start() throws Exception {
    
    
		System.out.println("准备中...");
		// 等待且获取socket对象
		Socket socket = ss.accept();
		//可以获取当前访问这IP
		System.out.println(socket.getLocalAddress().getHostAddress());
		// 获取socket中的输入流
		System.out.println("进入!");
		// 现在需要读取一个html文件作为返回,使用文件输入流
		FileInputStream fileInputStream = new FileInputStream(
				"本地地址.html");
		// 读取文件输入流中的内容
		InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
		// 再次包装,还是使用bufferedreader
		BufferedReader reader = new BufferedReader(inputStreamReader);
		// String readLine = reader.readLine();
		// 现在已经有了输入流,需要进行输出,浏览器已经获取到socket了,所以直接获取输出流
		OutputStream out = socket.getOutputStream();
		// 现在进行包装
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, "UTF-8");
		// 再次包装进打印流,printwriter
		PrintWriter writer = new PrintWriter(outputStreamWriter, true);
		/**
		 * 非常关键的代码,需要告诉浏览器,我是HTTP响应
		 */
		writer.println("HTTP/1.1 200 OK"); // 成功响应
		writer.println("Content-Type: text/html;charset=utf-8");// 响应类型与编码
		writer.println();
		// 一行一行的读取数据
		String readLine = "";
		while ((readLine = reader.readLine()) != null) {
    
    
			writer.println(readLine);
		}
		// 关流
		outputStreamWriter.close();
		inputStreamReader.close();
	}

	public static void main(String[] args) throws Exception {
    
    
		Webserver webserver = new Webserver();
		// 需要一直接收请求
		while (true) {
    
    
			webserver.start();
		}
	}
}

Guess you like

Origin blog.csdn.net/WLK0423/article/details/110240469
Recommended