无法发送与Java的Socket HTTP响应(Trouble sending HTTP respo

2019-06-24 12:51发布

我一直想写一个简单的Web服务器的开端,但似乎无法得到回应被发送。 我尝试过每一种类型的输出流可以想象,但似乎没有任何工作的。 我不知所措。 这里有两个类我使用,对一些外来代码的遗憾:

package edu.xsi.webserver;

import java.io.IOException;
import java.net.ServerSocket;


public class WebServer {

int port;
ServerSocket server;

public WebServer(int port) throws IOException{

    this.port = port;
    this.server = new ServerSocket(port);
    Thread t = new Thread(new ServerExec());
    t.start();

}

public class ServerExec implements Runnable {

    public void run(){

        int i = 0;
        while (true) {

            try {
                new WebSession(server.accept(), i++);
                System.out.println("Should print before session");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


}

public static void main(String[] args) {

    try {
        WebServer webServer = new WebServer(8888);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

这是处理响应的会话类。

package edu.xsi.webserver;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class WebSession implements Runnable {

Socket client;
int num;

public WebSession(Socket client, int num) {

    this.num = num;
    this.client = client;
    Thread t = new Thread(this);
    t.start();
}


public void run() {

    Scanner s = null;
    DataOutputStream out = null;

    try {

        s = new Scanner(client.getInputStream());
        out = new DataOutputStream(client.getOutputStream());

        //Get all input from header
        while (s.hasNextLine()) {
            System.out.println(s.nextLine());
        }
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: text/html\r\n\r\n");
        out.writeBytes("<html><head></head><body><h1>Hello</h1></body></html>");

        s.close();
        out.flush();
        out.close();

    } catch(IOException ioe) {

        ioe.printStackTrace();
    }

}

}

Answer 1:

我一直在努力想疯了一个非常类似的问题。

在我发现我的问题是这样微不足道的墙壁字面上头绑扎后我一直在头撞墙壁上一会儿。

基本上在我的输入while循环我检查了一个空行,但我忘了检查了一个空行 (以及随后突破)。

不保证它会工作的同样的话,但这里是我的一分:

in = session.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = br.readLine()) != null) {
    System.out.println(line);
    // this seems to be the key for me! 
    // somehow I never get out of this loop if I don't 
    // check for an empty line...
    if (line.isEmpty()) {
        break;
    }
}
out = new BufferedWriter(
    new OutputStreamWriter(
        new BufferedOutputStream(session.getOutputStream()), "UTF-8")
);
out.write(OUTPUT_HEADERS + OUTPUT.length() + OUTPUT_END_OF_HEADERS + OUTPUT);
out.flush();
out.close();
session.close();

我的常量是:

private static final String OUTPUT = "<html><head><title>Example</title></head><body><p>Worked!!!</p></body></html>";
private static final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" +
    "Content-Type: text/html\r\n" + 
    "Content-Length: ";
private static final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";

我的“会话”变量是一个Socket对象。



Answer 2:

关闭扫描仪关闭底层输入流,它关闭套接字。 不要关闭它。 关闭输出流也关闭套接字。 你不需要两个,你应该关闭输出流/写器,而不是输入流,因此被刷新。



Answer 3:

下面的代码将解决你的问题:

package com.cs.sajal;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TestCls {

    public static void main(String[] args) {
        boolean flag = false;

        try {
            ServerSocket ss = new ServerSocket(8080);
            if (ss.isBound()) {
                while (flag = true) {
                    final Socket s = ss.accept();



                    Thread t1=new Thread(new Runnable (){String line = null;public void run(){try{ InputStream is = s.getInputStream();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is));

                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                    }});

                    Thread t2=new Thread(new Runnable (){String line = null;public void run(){try{ OutputStream os = s.getOutputStream();
                    Scanner sc=new Scanner(System.in);
                    String inp=null;
                    String t="HTTP/1.1 200 OK\r\n";
                    byte[]s=t.getBytes("UTF-8");
                    os.write(s);

                    t="Content-Length: 788\r\n";
                    s=t.getBytes("UTF-8");
                    os.write(s);
                    t="Content-Type: text/html\r\n\r\n";
                    s=t.getBytes("UTF-8");
                    os.write(s);


                    t="\r\n\r\n<html><body><h1>this is output</h1><table cellpading=5 border=5><tr><td>name</td><td>age></td><td>height</td></tr></table></body></html>\r\n\r\n";
                    s=t.getBytes("UTF-8");
                    os.write(s);
                    t="Connection: Closed";
                    s=t.getBytes("UTF-8");
                    os.write(s);

                    os.flush();
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                    }});
                    t1.start();
                    t2.start();t1.join();
                    t2.join();


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Answer 4:

尝试通过之日起。

 String res = "HTTP/1.0 200 OK\n"
         + "Server: HTTP server/0.1\n";
         + "Date: "+format.format(new java.util.Date())+"\n"; 
   + "Content-type: text/html; charset=UTF-8\n"; 
         + "Content-Length: 38\n\n";
         + "<html><body>OK</body></html>";
out.write(res.getBytes());
out.flush();

private SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:Ss z");


文章来源: Trouble sending HTTP response with Java Socket