美文网首页Java 杂谈
一个简单的Java服务器

一个简单的Java服务器

作者: java高级编程中心 | 来源:发表于2019-05-14 22:12 被阅读2次

    /**

    *

    */

    package iotest.serversocket;

    importjava.io.BufferedInputStream;

    import java.io.BufferedOutputStream;

    import java.io.ByteArrayOutputStream;

    import java.io.FileInputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.OutputStream;

    import java.io.UnsupportedEncodingException;

    import java.net.ServerSocket;

    import java.net.Socket;

    /**

    * @author Brandon B. Lin

    *

    */

    public class SingleFileHttpServer extends Thread {

    private byte[] content;

    private byte[] header;

    private int port = 80;

    public SingleFileHttpServer(String data, String encoding, String MIMEType,

    int port) throws UnsupportedEncodingException {

    this(data.getBytes(encoding), encoding, MIMEType, port);

    }

    public SingleFileHttpServer(byte[] data, String encoding, String MIMEType,

    int port) throws UnsupportedEncodingException {

    this.content = data;

    this.port = port;

    createHeader(encoding, MIMEType);

    }

    private void createHeader(String encoding, String MIMEType)

    throws UnsupportedEncodingException {

    String header = "HTTP/1.0 200 OK " + "Server: OneFIle 1.0 "

    + "Content-length: " + content.length + " "

    + "Content-type: " + MIMEType + " ";

    this.header = header.getBytes(encoding);

    }

    @Override

    public void run() {

    try {

    ServerSocket server = new ServerSocket(port);

    log(server.getLocalPort());

    while (true) {

    respond(server);

    }

    } catch (IOException exception) {

    System.err.println("Could not start server. Port Occupied!");

    }

    }

    private void log(int port) {

    System.out.println("Accepting connection on port " + port);

    System.out.println("Data to be sent: ");

    try {

    System.out.write(content);

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    private void respond(ServerSocket server) {

    Socket connection = null;

    try {

    connection = server.accept();

    String request = readRequestFromSocket(connection);

    boolean writeHeader = (request.toString().indexOf("HTTP/") != -1);

    writeToSocket(connection, writeHeader);

    } catch (IOException e) {

    e.printStackTrace();

    } finally {

    if (connection != null)

    try {

    connection.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    其实做为一个开发者,有一个学习的氛围跟一个交流圈子特别重要这里我推荐一个Java交流群664389243,不管你是小白还是大牛欢迎入驻,大家一起交流成长。

    相关文章

      网友评论

        本文标题:一个简单的Java服务器

        本文链接:https://www.haomeiwen.com/subject/wojyaqtx.html