簡體   English   中英

Java服務器:套接字將HTML代碼發送到瀏覽器

[英]Java Server: Socket sending HTML code to 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語句中檢查輸出“ Connected”。 我也嘗試過從inputStream輸出數據,並且可以正常工作。 但是我嘗試在瀏覽器中輸出的文本根本沒有顯示,程序完成運行,我得到了

“問題加載頁面-連接已重置”

在我的瀏覽器中,但沒有文字。

我已經在互聯網上搜索了,似乎其他所有人都用這種方式編碼時,他們的文字顯示效果很好,他們還有其他問題。 我怎樣才能解決這個問題?

我在Chrome,Firefox,IE和Opera中測試了您的代碼,並且可以正常工作。

但是,我建議您使用多線程並從本質上產生一個新線程來處理每個新請求。

您可以創建一個實現可運行的類,並在構造函數中使用一個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. HTTP中的行終止符為\\r\\n. 這意味着您不應使用println() ,而應使用print()並在每行中添加一個顯式\\r\\n自己。

  2. HTTP GET的結果應該是HTML文檔,而不是片段。 瀏覽器有權忽略或投訴。 發送此:

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

您需要將PrintWriter設置為在打印時自動刷新。

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

應該

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

在我的計算機上,至少要獲取套接字的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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM