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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Server:Socket将HTML代码发送到浏览器相关的知识,希望对你有一定的参考价值。

我正在尝试使用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("
");
out.println("<p> Hello world </p>");
out.flush();

out.close();

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

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

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

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

我已经搜索过互联网,似乎其他所有人都用这种方式进行编码就是让文本显示正常,他们还有其他问题。我怎样才能解决这个问题?

答案

我在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" + "
";
FileInputStream fin = null;

if (statusCode == 200)
statusLine = "HTTP/1.1 200 OK" + "
";
else
statusLine = "HTTP/1.1 404 Not Found" + "
";

if (isFile) {
fileName = responseString;
fin = new FileInputStream(fileName);
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "
";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
contentTypeLine = "Content-Type: 
";
}
else {
responseString = myHTTPServer.HTML_START + responseString + myHTTPServer.HTML_END;
contentLengthLine = "Content-Length: " + responseString.length() + "
";
}

outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes("Connection: close
");
outToClient.writeBytes("
");

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. HTTP中的行终止符是 .这意味着你不应该使用println(),你应该使用print()并在每行添加一个明确的
  2. HTTP GET的结果应该是HTML文档,而不是片段。浏览者有权忽视或抱怨。发送此: <html> <head/> <body> <p> Hello world </p> </body> </html>
另一答案

在我的电脑中,至少要获取套接字的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;
}

另一答案

您应该接受客户端发送的请求(在本例中为浏览器),为此,只需添加以下行:

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();
    }
}
另一答案

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

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

应该

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

以上是关于Java Server:Socket将HTML代码发送到浏览器的主要内容,如果未能解决你的问题,请参考以下文章

java中Socket通信

将 c++ unix server/socket 连接到 java windows client/socket

python,socket网络编程,最简单的server端和client端代码

Python--网络编程-----socket代码实例

Java Socket Server-Client模式 2.0

Java Socket网络编程Server端详解