【发布时间】:2017-03-01 15:01:03
【问题描述】:
出于好奇,我正在尝试用 Java 构建 HTTP 服务器。
我知道 HTTP 在下面使用套接字(如果我错了,请纠正我)。于是开始使用ServerSocket 类开始编程。
public class Server
{
public static void main(String[] args) throws IOException
{
System.out.println("Listening.....");
ServerSocket ss = new ServerSocket(80);
while(true)
{
Socket s = ss.accept();
Scanner sc = new Scanner(s.getInputStream());
while(sc.hasNextLine())
{
String line = sc.nextLine();
if(line.equals(""))
break;
else
System.out.println(line);
}
System.out.println("-------------------------------");
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("Hello from Server");
s.close();
ps.close();
sc.close();
}
}
}
(我在实际代码中使用Thread 为多个用户提供服务。我刚刚提供了基本代码。)
我正在从网络浏览器获取所有标题。但是如何发送文件和图像?
对于简单的 HTML,我可以读取文件并使用 PrintStream 在网络浏览器上打印它。
但是如何将 JavaScript、图像等发送到浏览器?
【问题讨论】: