Java Server:Socket将HTML代码发送到浏览器

时间:2013-04-08 21:28:25

标签: java html sockets browser

我正在尝试使用ServerSockets编写一个简单的Java程序,它将向浏览器发送一些HTML代码。这是我的代码:

ServerSocket serverSocket = null;
try {
    serverSocket = new ServerSocket(55555); 
} catch (IOException e) {
    System.err.println("Could not listen on port: 55555.");
    System.exit(1);
}

Socket clientSocket = null; 
try {
    clientSocket = serverSocket.accept();

    if(clientSocket != null) {           
        System.out.println("Connected");
    }
} catch (IOException e) {
    System.err.println("Accept failed.");
    System.exit(1);
}

PrintWriter out = new PrintWriter(clientSocket.getOutputStream());


out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("\r\n");
out.println("<p> Hello world </p>");
out.flush();

out.close();

clientSocket.close();
serverSocket.close();

然后我在浏览器中转到localhost:55555,没有显示任何内容。我知道连接正在运行,因为程序在if语句中输出“已连接”。我也尝试从inputStream输出数据,这是有效的。但是我试图在浏览器中输出的文本根本没有显示,程序运行完毕,我得到了

  

“问题加载页面 - 连接已重置”

在我的浏览器中,但没有文字。

我已经在互联网上搜索了,似乎所有其他人都用这种方式编码就是让他们的文字显示得很好,他们还有其他问题。 我怎样才能解决这个问题?

5 个答案:

答案 0 :(得分:3)

我在Chrome,Firefox,IE和Opera中测试了您的代码,但它确实有用。

但是,我建议您使用多线程并基本上生成一个新线程来处理每个新请求。

您可以创建一个实现runnable的类,并在构造函数中获取一个clientSocket。这基本上使您的自定义Web服务器能够同时接受多个请求。

如果您想处理多个请求,还需要一个while循环。

一个很好的阅读证明了上述内容:https://web.archive.org/web/20130525092305/http://www.prasannatech.net/2008/10/simple-http-server-java.html

如果网络存档不起作用,我将发布以下代码(取自上面):

/*
* myHTTPServer.java
* Author: S.Prasanna
* @version 1.00
*/

import java.io.*;
import java.net.*;
import java.util.*;

public class myHTTPServer 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 myHTTPServer(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);
if (new File(fileName).isFile()){
sendResponse(200, fileName, true);
}
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);
}
}
}
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: \r\n";
}
else {
responseString = myHTTPServer.HTML_START + responseString + myHTTPServer.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);
}
fin.close();
}

public static void main (String args[]) throws Exception {

ServerSocket Server = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println ("TCPServer Waiting for client on port 5000");

while(true) {
Socket connected = Server.accept();
    (new myHTTPServer(connected)).start();
}
}
}

享受!

答案 1 :(得分:1)

  1. HTTP中的行终止符为\r\n.这意味着您不应使用println(),您应该使用print()并自行添加明确的\r\n每一行。

  2. HTTP GET的结果应该是HTML文档,而不是片段。浏览者有权忽视或抱怨。发送此:

    <html>
    <head/>
    <body>
    <p> Hello world </p>
    </body>
    </html>
    

答案 2 :(得分:1)

在我的电脑中,至少要获取套接字的inputStream:

clientSocket.getInputStream();

没有这条线,有时铬不起作用

您需要首先从套接字读取输入

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line = "";
while((line = bufferedReader.readLine()) != null){
    System.out.println(line);
    if(line.isEmpty())
        break;
}

答案 3 :(得分:1)

您应该接受客户端(在这种情况下为浏览器)发送的请求,只需添加以下几行即可:

Buffered reader in = new Buffered reader(new InputStreamReader(client_socket.getInputStream()));

注意:您需要用自己的客户端套接字名称替换“ client_socket”部分。

为什么我们需要接受浏览器请求? 这是因为如果我们不接受请求,浏览器就不会从服务器获得任何确认,即已接收到已发送的请求,因此它认为服务器不再可访问。

我的代码:

public class Help {
    public static void main(String args) throws IOException{
        ServerSocket servsock new serverSocket(80)
        Socket cs servsock, accept();
        Printwriter out new Printwriter(Cs.getoutputstream), true)
        BufferedReader in new BufferedReader(new InputStreamReader(cs.getInputStream());
        out.println("<html> <body> <p>My first StackOverflow answer </p> </body> </html>");
        out.close();
        servsock.close();
    }
}

答案 4 :(得分:0)

您需要在打印时将PrintWriter设置为autoflush。

PrintWriter out = new PrintWriter(clientSocket.getOutputStream());

应该是

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);