-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathServertcp6.java
More file actions
69 lines (61 loc) · 2.81 KB
/
Servertcp6.java
File metadata and controls
69 lines (61 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* @由于个人水平有限, 难免有些错误, 还请指点:
* @Author: cpu_code
* @Date: 2020-09-20 14:40:00
* @LastEditTime: 2020-09-20 14:41:57
* @FilePath: \java\network\Servertcp6.java
* @Gitee: [https://gitee.com/cpu_code](https://gitee.com/cpu_code)
* @Github: [https://github.com/CPU-Code](https://github.com/CPU-Code)
* @CSDN: [https://blog.csdn.net/qq_44226094](https://blog.csdn.net/qq_44226094)
* @Gitbook: [https://923992029.gitbook.io/cpucode/](https://923992029.gitbook.io/cpucode/)
*/
package network;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Servertcp6 {
public static void main(String[] args) throws IOException {
//创建一个服务器ServerSocket,和系统要指定的端口号
ServerSocket server = new ServerSocket(8080);
//使用accept方法获取到请求的客户端对象(浏览器)
Socket socket = server.accept();
//使用Socket对象中的方法getInputStream,获取到网络字节输入流InputStream对象
InputStream is = socket.getInputStream();
//使用网络字节输入流InputStream对象中的方法read读取客户端的请求信息
/*byte[] bytes = new byte[1024];
int len = 0;
while((len = is.read(bytes))!=-1){
System.out.println(new String(bytes,0,len));
}*/
//把is网络字节输入流对象,转换为字符缓冲输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//把客户端请求信息的第一行读取出来 GET /11_Net/web/index.html HTTP/1.1
String line = br.readLine();
//把读取的信息进行切割,只要中间部分 /11_Net/web/index.html
String[] arr = line.split(" ");
//把路径前边的/去掉,进行截取 11_Net/web/index.html
String htmlpath = arr[1].substring(1);
//创建一个本地字节输入流,构造方法中绑定要读取的html路径
FileInputStream fis = new FileInputStream(htmlpath);
//使用Socket中的方法getOutputStream获取网络字节输出流OutputStream对象
OutputStream os = socket.getOutputStream();
// 写入HTTP协议响应头,固定写法
os.write("HTTP/1.1 200 OK\r\n".getBytes());
os.write("Content-Type:text/html\r\n".getBytes());
// 必须要写入空行,否则浏览器不解析
os.write("\r\n".getBytes());
//一读一写复制文件,把服务读取的html文件回写到客户端
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
//释放资源
fis.close();
socket.close();
server.close();
}
}
/*
<img src="https://gitee.com/cpu_code/picture_bed/raw/master//20200920144146.png"/>
*/