1.创建ServerService类,该类是本项目的核心类,接收传入的端口号并进行处理,利用输入输出流和File类知识,对传入的端口号拼接,并模拟用户访问浏览器的请求信息,对网页发出请求并做出响应,将结果返回给ServerThread类
package service;
import java.io.*;
import java.net.Socket;
public class ServerService {
private Socket s;
private InputStream inputStream;
private OutputStream outputStream;
public ServerService(Socket s) {
this.s=s;
try {
this.inputStream=s.getInputStream();
this.outputStream=s.getOutputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.work();
}
private void work() {
while (true){
try {
byte[]bytes=new byte[1024];
int len=inputStream.read(bytes);
if (len!=-1){
String req=new String(bytes,0,len,"utf-8");
String fileName=req.split("\n")[0].split(" ")[1].substring(1);
File file=new File(fileName);
InputStream is=new FileInputStream(file);
outputStream.write("HTTP /1.1 200 ok\r\n".getBytes("utf-8"));
outputStream.write("Content-Type:text/html\r\n".getBytes("utf-8"));
outputStream.write(("Content-Length:" + file.length() + "\r\n").getBytes("utf-8"));
outputStream.write("\r\n".getBytes("utf-8"));
int len0=0;
byte[]bytes1=new byte[1024];
while ((len0=is.read(bytes1))!=-1){
outputStream.write(bytes1,0,len0);
}
outputStream.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
2.创建ServerThread类,编写run方法,调用ServerService类的,并将传入的端口号一并闯入到该类中,将结果返回到主函数输出
package thread;
import service.ServerService;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ServerThread extends Thread{
private Socket s;
public ServerThread(Socket s) {
this.s=s;
}
@Override
public void run() {
System.out.println(this.getName());
new ServerService(this.s);
}
}
3.创建Main类,创建一个服务器套接字(ServerSocket),在9999端口上监听传入的连接。当有连接被接受时,它会启动一个新的线程(ServerThread)来处理与客户端的通信,每当有新的连接到达时,都会创建一个新的线程来处理该连接,以避免阻塞主线程,实现服务器可以同时处理多个客户端的请求。
import thread.ServerThread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) {
System.out.println("启动服务");
try {
ServerSocket ss=new ServerSocket(9999);
while (true){
Socket s=ss.accept();
new ServerThread(s).start();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
4.运行结果