使用套接字从服务器向客户端发送静态文件

亚历山德罗

我在此代码上遇到了一些麻烦:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class WorkerRunnable implements Runnable, HttpServer {

    protected Socket clientSocket = null;
    protected String serverText = null;
    protected Map<String, String> paramMap = null;



    private String OK = "HTTP/1.0 200 OK",
            NOT_FOUND = "HTTP/1.0 404 Not Found",
            BAD_REQUEST = "HTTP/1.0 400 Bad Request",
            FORBIDDEN = "HTTP/1.0 403 Forbidden",
            SERVER_ERROR = "HTTP/1.0 500 Internal Server Error";

    public WorkerRunnable(Socket clientSocket, String serverText) {
        this.clientSocket = clientSocket;
        this.serverText = serverText;
    }

    public void run() {
        try {



            paramMap = parse(clientSocket.getInputStream());
            // response(clientSocket.getOutputStream(), paramMap);
            response(clientSocket.getOutputStream(), paramMap);

        } catch (IOException e) {
            // report exception somewhere.
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, String> parse(InputStream is) throws IOException {
        Map<String, String> paramMap = new HashMap<String, String>();
        LineNumberReader lr = new LineNumberReader(new InputStreamReader(is));
        String inputLine = null;
        String method = null;
        String httpVersion = null;
        String uri = null;

        // read request line
        inputLine = lr.readLine();
        String[] requestCols = inputLine.split("\\s");
        method = requestCols[0];
        uri = requestCols[1];
        httpVersion = requestCols[2];
        System.out.println("http version:\t" + httpVersion);

        // read header
        while (StringUtils.isNotBlank(inputLine = lr.readLine())) {
            System.out.println("post header line:\t" + inputLine);
        }

        // parse GET param
        if (uri.contains("?")) {
            paramMap.putAll(parseParam(uri.split("\\?", 2)[1], false));
            System.out.println("get body:\t" + paramMap.toString());
        } else if (method.toUpperCase().equals("POST")) {
            // read body - POST method
            StringBuffer bodySb = new StringBuffer();
            char[] bodyChars = new char[1024];
            int len;

            // ready() make sure it will not block,
            while (lr.ready() && (len = lr.read(bodyChars)) > 0) {
                bodySb.append(bodyChars, 0, len);
            }
            paramMap.putAll(parseParam(bodySb.toString(), true));

            System.out.println("post body:\t" + bodySb.toString());
        } else {
            System.out.println("home");
        }

        return paramMap;
    }

    @Override
    public Map<String, String> parseParam(String paramStr, boolean isBody) {
        String[] paramPairs = paramStr.trim().split("&");
        Map<String, String> paramMap = new HashMap<String, String>();

        String[] paramKv;
        for (String paramPair : paramPairs) {
            if (paramPair.contains("=")) {
                paramKv = paramPair.split("=");
                if (isBody) {
                    // replace '+' to ' ', because in body ' ' is replaced by
                    // '+' automatically when post,
                    paramKv[1] = paramKv[1].replace("+", " ");
                }
                paramMap.put(paramKv[0], paramKv[1]);
            }
        }

        return paramMap;
    }

    @Override
    // public void response(OutputStream os, Map<String, String> paramMap) {
    // String name = StringUtils.isBlank(paramMap.get("name")) ? "xxx"
    // : paramMap.get("name");
    //
    // String comando = StringUtils.isBlank(paramMap.get("comando")) ? "xxx"
    // : paramMap.get("comando");
    //
    // PrintWriter pw = null;
    // pw = new PrintWriter(os);
    // pw.println("HTTP/1.1 200 OK");
    // pw.println("Content-type: text/html; Charset=UTF-8");
    // pw.println("");
    // pw.println("<h1>Hi <span style='color: #FFF; background: #000;'>"
    // + name + "</span> !</h1>");
    // pw.println("<h4>current date: " + new Date() + "</h4>");
    // pw.println("<p>you can provide your name via a param called <span style='color: #F00; background: yellow;'>\"name\"</span>, in both GET and POST method.</p>");
    // pw.flush();
    // pw.close();
    //
    // }
    public void response(OutputStream out, Map<String, String> paramMap) {
        File file = new File("pageClient.html");
        String mimeType = getMimeType(file);
        sendFile(file, mimeType, file.getName());
    }

    /* Sends the requested file to the client */
    public void sendFile(File file, String fileType, String fileName) {
        try {
            PrintStream send = new PrintStream(clientSocket.getOutputStream());
            // Buffer must not be to low, => fragments
            int length = 0; // (int) file.length();
            FileInputStream fileIn = new FileInputStream(fileName);
            byte[] bytes = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            /* Write until bytes is empty */
            while ((length = fileIn.read(bytes)) != -1 ){
                bos.write(bytes, 0, length);
                // send.write(bytes, 0, length);
                // send.flush();
            }
            bos.flush();
            bos.close();
            byte[] data1 = bos.toByteArray();

            System.out.print(new String(data1));
            send.print(OK);
            send.print("");
            send.print("Content-Type: " + fileType + "\r\n");
            send.println("");
            send.write(data1, 0, data1.length);
            send.println("");

            send.flush();
            send.close();

            fileIn.close();
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

    /* Finds out the MIME type of the requested file */
    public String getMimeType(File f) {
        String file = f.toString();
        String type = "";
        if (file.endsWith(".txt")) {
            type = "text/txt";
        } else if (file.endsWith(".html") || file.endsWith("htm")) {
            type = "text/html; Charset=UTF-8";
        } else if (file.endsWith(".jpg")) {
            type = "image/jpg";
        } else if (file.endsWith(".png")) {
            type = "image/png";
        } else if (file.endsWith(".jpeg")) {
            type = "image/jpeg";
        } else if (file.endsWith(".gif")) {
            type = "image/gif";
        } else if (file.endsWith(".pdf")) {
            type = "application/pdf";
        } else if (file.endsWith(".mp3")) {
            type = "audio/mpeg";
        } else if (file.endsWith(".class")) {
            type = "application/octet-stream";
        } else if (file.endsWith(".mp4")) {
            type = "video/mp4";
        }
        return type;
    }
}

在注释中,有一种方法的可能解决方案response,它很好用!完美!但是我的目标是为发送一个简单的文件“ pageClient.html”,response但是这样做有些麻烦

问题出在那个函数里面: public void sendFile(File file, String fileType, String fileName)

我的代码步骤为:打开浏览器;写链接:localhost:xxxx,服务器向我发送了一个homepage.html

似乎很简单:-(

但是现在服务器仅向我发送一个无效页面(浏览器,另外下载...)有人可以帮助我吗?

11维

在下面的try方法中,我sendFile()在commented方法的基础上进行了修改response()这应该工作。

public void sendFile(File file, String fileType, String fileName) {
    try {
        PrintStream send = new PrintStream(clientSocket.getOutputStream());
        // Buffer must not be to low, => fragments
        int length = 0; // (int) file.length();
        FileInputStream fileIn = new FileInputStream(fileName);
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        /* Write until bytes is empty */
        while ((length = fileIn.read(bytes)) != -1) {
            bos.write(bytes, 0, length);
            // send.write(bytes, 0, length);
            // send.flush();
        }
        bos.flush();
        bos.close();
        byte[] data1 = bos.toByteArray();

        String dataStr = new String(data1, "UTF-8");

        System.out.print(dataStr);
        send.println("HTTP/1.1 200 OK");
        send.println("Content-type: "+ fileType+ "; Charset=UTF-8");
        send.println("");
        send.println(dataStr);

        send.flush();
        send.close();

        fileIn.close();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

编辑:较短的版本,没有在内存中加载文件

IOUtils来自Apache Commons IO库

public void sendFile(File file, String fileType, String fileName) {
    try (OutputStream send = new BufferedOutputStream(clientSocket.getOutputStream());
        InputStream fileIn = new BufferedInputStream(new FileInputStream(fileName));) {

        String httpHeader = "";
        httpHeader += "HTTP/1.1 200 OK\n";
        httpHeader += "Content-type: "+ fileType+ "; Charset=UTF-8\n";
        httpHeader += "\n";

        send.write(httpHeader.getBytes("UTF-8"););
        send.flush();

        IOUtils.copy(fileIn, send);
        send.flush();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Spring Integration和TCP服务器套接字-如何向客户端发送消息?

来自分类Dev

Python套接字服务器/客户端编程

来自分类Dev

使用Java中的套接字将文件从服务器下载到客户端

来自分类Dev

套接字io,节点js,从服务器向客户端发送图像/文件的简单示例

来自分类Dev

通过python中的TCP套接字在客户端-服务器之间发送文件?

来自分类Dev

使用C中的套接字将文件从客户端发送到服务器

来自分类Dev

使用Python使客户端套接字等待服务器套接字

来自分类Dev

使用套接字在客户端阻止的客户端-服务器通信

来自分类Dev

使用套接字将值从服务器发送到客户端

来自分类Dev

如何将数据从Web套接字服务器发送到客户端?

来自分类Dev

客户端套接字未完全收到服务器端套接字发送的内容

来自分类Dev

如何使用Java / Java脚本从服务器发送图像到客户端web套接字?

来自分类Dev

套接字服务器无法接收客户端发送的消息

来自分类Dev

TCP套接字,发送文件,客户端服务器,服务器不保存整个文件,C语言

来自分类Dev

使用python套接字将Txt文件从客户端发送到服务器

来自分类Dev

通过ActionScript服务器和Java客户端之间的套接字发送对象

来自分类Dev

如何使用客户端套接字作为服务器套接字python

来自分类Dev

使用套接字C#客户端/服务器发送文件

来自分类Dev

Java套接字-将数据从服务器发送到客户端

来自分类Dev

从客户端向服务器发送字符串,然后保存文件(使用C)

来自分类Dev

如何使用Java中的套接字从服务器向特定客户端发送字符串消息?

来自分类Dev

通过python中的TCP套接字在客户端-服务器之间发送文件?

来自分类Dev

服务器无法通过C中的套接字向客户端发送消息

来自分类Dev

Java多线程套接字客户端/服务器:发送和接收Enummap对象

来自分类Dev

Java套接字-将数据从客户端发送到服务器

来自分类Dev

套接字发送客户端服务器文件

来自分类Dev

从Node JS Socket客户端向MINA套接字服务器发送消息

来自分类Dev

C posix套接字,无法从客户端向服务器发送数据

来自分类Dev

在套接字客户端服务器中发送多个文件

Related 相关文章

  1. 1

    Spring Integration和TCP服务器套接字-如何向客户端发送消息?

  2. 2

    Python套接字服务器/客户端编程

  3. 3

    使用Java中的套接字将文件从服务器下载到客户端

  4. 4

    套接字io,节点js,从服务器向客户端发送图像/文件的简单示例

  5. 5

    通过python中的TCP套接字在客户端-服务器之间发送文件?

  6. 6

    使用C中的套接字将文件从客户端发送到服务器

  7. 7

    使用Python使客户端套接字等待服务器套接字

  8. 8

    使用套接字在客户端阻止的客户端-服务器通信

  9. 9

    使用套接字将值从服务器发送到客户端

  10. 10

    如何将数据从Web套接字服务器发送到客户端?

  11. 11

    客户端套接字未完全收到服务器端套接字发送的内容

  12. 12

    如何使用Java / Java脚本从服务器发送图像到客户端web套接字?

  13. 13

    套接字服务器无法接收客户端发送的消息

  14. 14

    TCP套接字,发送文件,客户端服务器,服务器不保存整个文件,C语言

  15. 15

    使用python套接字将Txt文件从客户端发送到服务器

  16. 16

    通过ActionScript服务器和Java客户端之间的套接字发送对象

  17. 17

    如何使用客户端套接字作为服务器套接字python

  18. 18

    使用套接字C#客户端/服务器发送文件

  19. 19

    Java套接字-将数据从服务器发送到客户端

  20. 20

    从客户端向服务器发送字符串,然后保存文件(使用C)

  21. 21

    如何使用Java中的套接字从服务器向特定客户端发送字符串消息?

  22. 22

    通过python中的TCP套接字在客户端-服务器之间发送文件?

  23. 23

    服务器无法通过C中的套接字向客户端发送消息

  24. 24

    Java多线程套接字客户端/服务器:发送和接收Enummap对象

  25. 25

    Java套接字-将数据从客户端发送到服务器

  26. 26

    套接字发送客户端服务器文件

  27. 27

    从Node JS Socket客户端向MINA套接字服务器发送消息

  28. 28

    C posix套接字,无法从客户端向服务器发送数据

  29. 29

    在套接字客户端服务器中发送多个文件

热门标签

归档