我想实现一个仅服务于静态页面的web服务器。 这是我的超迷你网络服务器的代码。mozilla firefox意外的行为
import java.io.*;
import java.net.*;
class MyWebServer{
static ServerSocket serSocket = null ;
static{
try {
serSocket = new ServerSocket(80) ;
System.out.println("Server started successfully....\n\n") ;
} catch (IOException io) {
System.out.println(io.getMessage());
System.exit(1) ;
}
}
public static void main(String []args){
while(true){
try {
new Thread(new ServingThread(serSocket.accept())).start() ;
} catch (IOException io) {
System.out.println(io.getMessage());
}
}
}
}
class ServingThread implements Runnable{
private Socket socket ;
public ServingThread(Socket socket){
this.socket = socket ;
System.out.println("Receives a new browser request from " + socket);
}
public void run() {
BufferedReader in = null ;
PrintWriter out = null ;
try {
//reading request headers from browser starts here
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = ".";
while (!str.equals("")){
str = in.readLine();
//System.out.println(str);
}
System.out.println("\n\n");
//reading request headers from browser ends here
//writing output on outputstream starts here
out = new PrintWriter(socket.getOutputStream(), true) ;
int i = (int) (Math.random() * 10) ;
out.println(i) ;
System.out.println(i) ;
//writing output on outputstream ends here
socket.close() ;
System.out.println("Request successfully fulfilled.\n") ;
}
catch (IOException io) {
System.out.println(io.getMessage());
}
}
}
它工作正常,但有时(并不总是)
- 我的Mozilla Firefox浏览器客户端 自动发送一个请求,当我 添加新的选项卡(按Ctrl + T)或关闭一个 现有选项卡。
- 当我要求 http://localhost/,在我的浏览器上显示一个数字。但 服务器的控制台显示它获得2度 或3的要求,因此,它显示 相应的2首或3个数字。
我GOOGLE了很多,但没有得到一个满意的答案。
任何想法/解释非常感谢。 :)
它是否必须是Java?这是一个Ruby中的超小型Web服务器,可以从Mac,Windows和Linux上的USB驱动器运行。 Pinky:http://yellosoft.us/index.php?id=86 – mcandre 2009-08-17 17:44:01
是的,我正在使用java。任何java链接:-)。 – mogli 2009-08-17 18:01:29