3

我正在尝试编写一个简单的 Java 程序,使用ServerSockets它将向浏览器发送一些 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 输出数据并且有效。但是我试图在浏览器中输出的文本根本没有显示,程序完成运行,我得到一个

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

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

我已经在互联网上搜索过,似乎其他人都以这种方式编码,他们的文本显示很好,他们还有其他问题。我怎样才能解决这个问题?

4

5 回答 5

4

我在 Chrome、Firefox、IE 和 Opera 中测试了您的代码,并且可以正常工作。

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

您可以创建一个实现 runnable 并在构造函数中采用 clientSocket 的类。这实质上将使您的自定义网络服务器能够同时接受多个请求。

如果要处理多个请求,还需要一个 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();
}
}
}

享受!

于 2013-04-08T21:54:08.237 回答
1
  1. HTTP 中的行终止符是\r\n.这意味着你不应该使用println(),你应该使用print()并在每一行添加一个显式的\r\n自己。

  2. HTTP GET 的结果应该是一个 HTML 文档,而不是一个片段。浏览器有权忽略或抱怨。发送这个:

    <html>
    <head/>
    <body>
    <p> Hello world </p>
    </body>
    </html>
    
于 2013-04-09T00:32:17.257 回答
1

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

clientSocket.getInputStream();

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

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

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

于 2018-03-16T08:35:15.860 回答
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();
    }
}
于 2018-09-06T11:12:33.243 回答
1

您需要在打印时将 PrintWriter 设置为自动刷新。

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

应该

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

于 2016-09-15T23:23:31.863 回答