使用java的小http服务器? [英] Small http server using java?

查看:111
本文介绍了使用java的小http服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java创建了以下测试服务器:

I have created the following test server using java:

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

class tcpServer{
    public static void main(String args[]){
        ServerSocket s = null;
        try{
            s = new ServerSocket(7896);
            //right now the stream is open.
            while(true){
                Socket clientSocket = s.accept();
                Connection c = new Connection(clientSocket);
                //now the connection is established
            }
        }catch(IOException e){
            System.out.println("Unable to read: " + e.getMessage());
        }
    }
}
class Connection extends Thread{
    Socket clientSocket;
    BufferedReader din;
    OutputStreamWriter outWriter;

    public Connection(Socket clientSocket){
        try{
            this.clientSocket = clientSocket;
            din = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "ASCII"));
            outWriter = new OutputStreamWriter(clientSocket.getOutputStream());
            this.start();
        }catch(IOException e){
            System.out.println("Connection: " + e.getMessage());
        }   
    }
    public void run(){
        try{
        String line = null;
        while((line = din.readLine())!=null){
            System.out.println("Read" + line);
            if(line.length()==0)    
                break;
        }
        //here write the content type etc details:
        System.out.println("Someone connected: " + clientSocket);
        outWriter.write("HTTP/1.1 200 OK\r\n");
        outWriter.write("Date: Tue, 11 Jan 2011 13:09:20 GMT\r\n");
        outWriter.write("Expires: -1\r\n");
        outWriter.write("Cache-Control: private, max-age=0\r\n");
        outWriter.write("Content-type: text/html\r\n");
        outWriter.write("Server: vinit\r\n");
        outWriter.write("X-XSS-Protection: 1; mode=block\r\n");
        outWriter.write("<html><head><title>Hello</title></head><body>Hello world from my server</body></html>\r\n");
        }catch(EOFException e){
            System.out.println("EOF: " + e.getMessage());
        }
        catch(IOException e){
            System.out.println("IO at run: " + e.getMessage());
        }finally{
            try{
                            outWriter.close();  
                clientSocket.close();
            }catch(IOException e){
                System.out.println("Unable to close the socket");
            }
        }
    }
}

现在我希望这台服务器响应我的浏览器。这就是为什么我给了url: http:// localhost:7896
因此我在服务器端收到:

Now i want this server to respond to my browser. that's why i gave url: http://localhost:7896 and as a result i receive at the server side:

ReadGET / HTTP/1.1
ReadHost: localhost:7896
ReadConnection: keep-alive
ReadCache-Control: max-age=0
ReadAccept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
ReadUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10
ReadAccept-Encoding: gzip,deflate,sdch
ReadAccept-Language: en-US,en;q=0.8
ReadAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
ReadCookie: test_cookie=test cookie
Read
Someone connected: Socket[addr=/0:0:0:0:0:0:0:1,port=36651,localport=7896]

我的浏览器和源代码的空白屏幕也是空白。在谷歌浏览器中。

And a blank white screen at my browser and source code also blank. In google chrome browser.

所以任何人都可以告诉我哪里错了。实际上我是这个新手。所以请纠正我。

So can anyone please tell me where i m wrong. actually i am new to this thing. so please correct me.

提前致谢

推荐答案

你几乎当然不希望在响应上使用 DataOutputStream - 而 writeUTF 肯定不会对你做什么想。 DataOutputStream 是为二进制协议设计的,基本上 - 和 writeUTF 写一个长度为前缀的UTF-8字符串,而HTTP只是想要CRLF终止的ASCII文本行。

You almost certainly don't want to be using DataOutputStream on the response - and writeUTF certainly isn't going to do what you want. DataOutputStream is designed for binary protocols, basically - and writeUTF writes a length-prefixed UTF-8 string, whereas HTTP just wants CRLF-terminated lines of ASCII text.

你想一次用行写出标题 - 所以创建一个 OutputStreamWriter 围绕套接字输出流,并写入:

You want to write headers out a line at a time - so create an OutputStreamWriter around the socket output stream, and write to that:

writer.write("HTTP/1.1 200 OK\r\n");
writer.write("Date: Tue, 11 Jan 2011 13:09:20 GMT\r\n");

等。

你可能想要编写自己的 writeLine 方法,在末尾写出包含CRLF的行(不要使用系统默认行终止符),以使代码更清晰。

You may want to write your own writeLine method to write out a line including the CRLF at the end (don't use the system default line terminator), to make the code cleaner.

在标题和正文之间添加一个空行,然后你应该处于合理的状态。

Add a blank line between the headers and the body as well, and then you should be in reasonable shape.

编辑:还有两个更改:

首先,您应该从客户端读取请求。例如,将 din 更改为 BufferedReader ,并将其初始化为:

Firstly, you should read the request from the client. For example, change din to a BufferedReader, and initialize it like this:

din = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),
                                               "ASCII"));

然后在开始写输出之前,请按以下方式读取请求:

then before you start to write the output, read the request like this:

String line;
while ((line = din.readLine()) != null) {
    System.out.println("Read " + line);
    if (line.length() == 0) {
        break;
    }
}

编辑:如评论中所述,这不会适用于完整的HTTP服务器,因为它不能很好地处理二进制PUT / POST数据(它可能会将数据读入其缓冲区,这意味着您无法将其作为流中的二进制数据读取)。这对于测试应用程序来说很好。

As noted in comments, this wouldn't be appropriate for a full HTTP server, as it wouldn't handle binary PUT/POST data well (it may read the data into its buffer, meaning you couldn't then read it as binary data from the stream). It's fine for the test app though.

最后,您还应关闭输出编写器或至少刷新它 - 否则它可能正在缓冲数据。

Finally, you should also either close the output writer or at least flush it - otherwise it may be buffering the data.

进行这些更改后,您的代码对我有效。

After making those changes, your code worked for me.

这篇关于使用java的小http服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆