package CC.Day12;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
String[] s = line.split(" ");
String path = s[1].substring(1);
FileInputStream fis = new FileInputStream(path);
System.out.println(path);
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());
int len = 0 ;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
fis.close();
os.close();
is.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
|
|