1

我正在为http尝试一个简单的java代码,如果我使用带有文件位置的chrome(http://localhost:8888/somefile.mp3)它工作正常,但如果我在iphone上使用safari,它会抛出错误: java.net.SocketException: Broken pipe 但如果我使用 LAMP 或任何 php 服务器,它工作正常。我怎样才能让它与java一起工作?

这是http服务器:

package com.streamternet;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.StringTokenizer;

public class HTTPServer extends Thread {

static final String HTML_START =
        "<html>" +
                "<title>HTTP Server in java</title>" +
                "<body>";

static final String HTML_END =
        "</body>" +
                "</html>";

Socket connectedClient = null;
BufferedReader inFromClient = null;
DataOutputStream outToClient = null;


public HTTPServer(Socket client) {
    connectedClient = client;
}

public void run() {

    try {

        System.out.println( "The Client "+
                connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");

        inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
        outToClient = new DataOutputStream(connectedClient.getOutputStream());

        String requestString = inFromClient.readLine();
        String headerLine = requestString;

        StringTokenizer tokenizer = new StringTokenizer(headerLine);
        String httpMethod = tokenizer.nextToken();
        String httpQueryString = tokenizer.nextToken();

        StringBuffer responseBuffer = new StringBuffer();
        responseBuffer.append("<b> This is the HTTP Server Home Page.... </b><BR>");
        responseBuffer.append("The HTTP Client request is ....<BR>");

        System.out.println("The HTTP request string is ....");
        while (inFromClient.ready())
        {
            // Read the HTTP complete HTTP Query
            responseBuffer.append(requestString + "<BR>");
            System.out.println(requestString);
            requestString = inFromClient.readLine();
        }

        if (httpMethod.equals("GET")) {
            if (httpQueryString.equals("/")) {
                // The default home page
                sendResponse(200, responseBuffer.toString(), false);
            } else {
                //This is interpreted as a file name
                String fileName = httpQueryString.replaceFirst("/", "");
                fileName = URLDecoder.decode(fileName);
                fileName="/"+fileName;
                if (new File(fileName).isFile()){
                    sendResponse(200, fileName, true);
                }
                else {
                    sendResponse(404, "<b>The Requested resource not found ....</b>", false);
                }
            }
        }
        else sendResponse(404, "<b>The Requested resource not found ...." +
                "Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void sendResponse (int statusCode, String responseString, boolean isFile) throws Exception {

    String statusLine = null;
    String serverdetails = "Server: Java HTTPServer";
    String contentLengthLine = null;
    String fileName = null;
    String contentTypeLine = "Content-Type: text/html" + "\r\n";
    FileInputStream fin = null;

    if (statusCode == 200)
        statusLine = "HTTP/1.1 200 OK" + "\r\n";
    else
        statusLine = "HTTP/1.1 404 Not Found" + "\r\n";

    if (isFile) {
        fileName = responseString;
        fin = new FileInputStream(fileName);
        contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
        if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
            contentTypeLine = "Content-Type: audio/mpeg\r\n";
    }
    else {
        responseString = HTTPServer.HTML_START + responseString + HTTPServer.HTML_END;
        contentLengthLine = "Content-Length: " + responseString.length() + "\r\n";
    }

    outToClient.writeBytes(statusLine);
    outToClient.writeBytes(serverdetails);
    outToClient.writeBytes(contentTypeLine);
    outToClient.writeBytes(contentLengthLine);
    outToClient.writeBytes("Connection: close\r\n");
    outToClient.writeBytes("\r\n");

    if (isFile) 
        sendFile(fin, outToClient);
    else 
        outToClient.writeBytes(responseString);

    outToClient.close();
}

public void sendFile (FileInputStream fin, DataOutputStream out) throws Exception {
    byte[] buffer = new byte[1024] ;
    int bytesRead;

    while ((bytesRead = fin.read(buffer)) != -1 ) {
        out.write(buffer, 0, bytesRead);
        out.flush();
    }
    fin.close();
}

public static void main (String args[]) throws Exception {

    ServerSocket Server = new ServerSocket (8888);

    System.out.println ("TCPServer Waiting for client on port 8888");

    while(true) {
        Socket connected = Server.accept();
        (new HTTPServer(connected)).start();
    }
}
}
4

1 回答 1

3

首先,这不是流式传输,这只是一个普通的 HTTP 请求-响应对话。看看你的服务器,它似乎在很多方面都被破坏了,甚至很难说为什么 Chrome 会设法下载任何东西。

我在网上放了一个最小的 HTTP 服务器,只是为了好玩。它远未完成,它不可配置并且仅支持GET请求,但是我认为如果您不想依赖其他服务器或框架,这是一个很好的起点。它只能给出两种响应:200 OK404 NOT FOUND。在 CLASSPATH 上搜索资源,并与基于扩展的 MIME 类型信息一起发送到客户端。您可能想要添加 MP3 MIME,但请注意,这只是一个玩具,仅用于展示 HTTP 的基础知识。

编码:

public class TinyHTTPServer {

    public static void main(String[] args) throws IOException {

        ServerSocket server = new ServerSocket(8888);

        while (true) {
            final Socket connection = server.accept();
            new Thread(new Runnable(){
                public void run() {
                    RequestHandler handler = new RequestHandler();
                    handler.handle(connection);
                }
            }).start();
        }
    }

    public static class RequestHandler {

        public void handle(Socket socket) {
            try {
                Scanner scanner = new Scanner(socket.getInputStream(), "US-ASCII");
                String path = getPath(scanner.nextLine());

                Response response = find(path);

                PrintStream out = new PrintStream(socket.getOutputStream());

                for (String header : response.headers) {
                    out.print(header);
                    out.print("\r\n");
                }

                out.print("\r\n");
                if (response.url != null)
                    writeEntity(response.url.openStream(), socket.getOutputStream());
                out.print("\r\n");

                out.flush();
            } catch (Exception exception) {
                exception.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private String getPath(String requestLine) throws IOException {
            Matcher matcher = Pattern.compile("GET (/\\S*) HTTP/1\\.1").matcher(requestLine);
            matcher.find();
            return matcher.group(1);
        }

        private Response find(String path) {

            if (path.equals("/"))
                path = "/index.html";

            Response response = new Response();
            URL url = RequestHandler.class.getResource(path);

            if (url == null) {
                response.headers.add("HTTP/1.1 404 NOT FOUND");
            } else {
                response.url = url;
                response.headers.add("HTTP/1.1 200 OK");

                String type = "application/octet-stream";
                String extension = url.toString();

                if (extension.endsWith(".mp3"))
                    type = "audio/mp3";
                else if (extension.endsWith(".html"))
                    type = "text/html; charset=utf-8";

                response.headers.add("Content-Type: " + type);
            }

            return response;
        }

        private void writeEntity(InputStream in, OutputStream out) throws IOException {
            byte[] buffer = new byte[1024];
            int read = -1;

            while ((read = in.read(buffer, 0, buffer.length)) > -1) {
                out.write(buffer, 0, read);
            }
        }

    }

    public static class Response {

        public List<String> headers = new LinkedList<String>();
        public URL url;

    }
}
于 2012-12-12T01:01:19.840 回答