Come trasmettere musica usando java come server?


Sto cercando un semplice codice java per http, se uso Chrome con il percorso del file (http://localhost:8888/somefile.mp3) funziona bene, ma se sto usando safari su iPhone, sta lanciando un errore: java. net. SocketException: tubo rotto ma se uso LAMP o qualsiasi server php, funziona bene. come posso farlo funzionare anche con java?

Questo è il server 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();
    }
}

}

Author: Dima, 2012-12-12

1 answers

Prima di tutto, questo non è streaming, questa è solo una semplice conversazione richiesta-risposta HTTP. Guardando il vostro server, sembra rotto in un certo numero di modi che è anche difficile dire perché Chrome riesce a scaricare nulla.

Ho messo un server HTTP minimo online, solo per divertimento. È tutt'altro che completo, non è configurabile e supporta solo le richieste GET, tuttavia penso che sia un buon punto di partenza se non si desidera fare affidamento su un altro server o framework. Può dare solo due tipi di risposte: 200 OK e 404 NOT FOUND. Le risorse vengono ricercate sul CLASSPATH e vengono inviate al client insieme alle informazioni sul tipo MIME in base all'estensione. Si consiglia di aggiungere il MIME MP3, ma si prega di notare che è solo un giocattolo ed è solo lo scopo di mostrare le basi di HTTP.

Il codice:

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;

    }
}
 2
Author: Raffaele, 2012-12-12 01:01:19