如何使用java作为服务器流式传输音乐?

时间:2012-12-11 22:23:28

标签: java stream webserver mp3

我正在为http尝试一个简单的java代码, 如果我使用chrome与文件位置(http:// localhost:8888 / somefile.mp3) 它工作正常,但如果我在iPhone上使用safari,它会抛出错误:         java.net.SocketException:管道损坏 但如果我使用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();
    }
}

}

1 个答案:

答案 0 :(得分:2)

首先,这不是 streaming ,这只是一个简单的HTTP请求 - 响应对话。看看你的服务器,它似乎在许多方面被打破,甚至很难说为什么Chrome设法下载任何东西。

我放了minimal HTTP server online,只是为了好玩。它远非完整,它不可配置且仅支持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;

    }
}