运行基本Web服务器

时间:2012-05-04 20:02:11

标签: java web

我编写了一个实现基本Web服务器的java类。它从控制台获取端口号。这段代码非常基础,它返回客户端发送的内容。这是代码:

package p106;

import java.io.*;
import java.net.*;

public class HttpMirror {

public static void main(String[] args) {

    try
    {
        int port = Integer.parseInt(args[0]);

        ServerSocket ss = new ServerSocket(port);

        for(;;)
        {
            Socket client = ss.accept();

            BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());

            out.print("HTTP/1.0 200 en");
            out.print("Content-Type text/plain");

            String line;
            while( (line = in.readLine()) != null)
            {
                if(line.length() == 0)
                    break;
                out.print(line );

            }

            out.close();
            in.close();
            client.close();

        } // Tekrar döngüye gir ve bir sonraki bağlantıyı bekle. 
    }catch(Exception e)
    {
        System.err.println(e);
    }

}

}

我运行此代码,我必须写入浏览器的地址栏? 提前致谢。

3 个答案:

答案 0 :(得分:4)

您是否尝试过localhost:端口号?或者127.0.0.1:这里的端口号

例如,如果端口号为8050,则地址为 localhost:8050 127.0.0.1:8050

答案 1 :(得分:2)

您没有指定用于启动Java引擎的命令。

  int port = Integer.parseInt(args[0]);

表示端口在命令行上传递。所以无论你在那里传递什么端口,你都应该放入你的网络浏览器。

例如:

java HttpMirror 12345
http://localhost:12345

答案 2 :(得分:0)

首先,您需要检查端口,然后http://localhost:Portnumber,例如http://localhost:8050