[英]Java, local TCP server accepting HTTP requests from a browser
我正在嘗試“編寫一個Java程序,該程序是一個TCP服務器,它向瀏覽器返回HTTP響應,該瀏覽器顯示客戶端的IP地址及其連接到服務器的次數”
目前我認為正在發生。 我正在創建服務器,並監聽請求的端口(作為參數的輸入),然后填充字節數組並將該數組轉換為字符串。 我希望現在就可以看到請求。
我的問題是,如果我確實嘗試通過轉到Web瀏覽器並鍵入“ localhost:1235”來連接到該服務器,則我的瀏覽器會一直說“正在連接至...”,而我的程序卻什么也沒做,只是坐着等待。
我將如何解決/實施其余的工作? 我當前的問題是什么?
到目前為止,這是我的代碼
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPHTTP
{
private static final int MAXFILELEN = 4096000;
static byte[] request = new byte[MAXFILELEN];
static String[] log;
public static void main (String args[])
{
if (args.length != 1)
throw new IllegalArgumentException( "Parameter(s): <Port>");
int port = Integer.parseInt(args[0]);
ServerSocket socket = null;
Socket sock = null;
try
{
socket = new ServerSocket(port);
}
catch (IOException e)
{
return;
}
for (;;)
{
try
{
sock = socket.accept();
InputStream is = sock.getInputStream();
int offset = 0;
int len = 0;
while ((len = is.read(request, offset, MAXFILELEN - offset)) >= 0)
{
offset += len;
}
String s = new String(request);
System.out.println(s);
// Add the users IP to the log
String from = "From: ";
int loglen = log.length;
int indexOfSenderIP = s.indexOf(from, 0);
indexOfSenderIP += from.length();
int indexOfNewline = s.indexOf("\n", indexOfSenderIP);
String sendersIP = s.substring(indexOfSenderIP, indexOfNewline);
log[loglen] = sendersIP;
//Find out how many times the sender IP appears in the log
int timesVisited = 0;
for(int i = 0; i < log.length; i++)
if(log[i].endsWith(sendersIP))
timesVisited++;
// Construct the HTTP response message
String httpResponse = "";
OutputStream os = sock.getOutputStream();
os.write(httpResponse.getBytes());
os.close();
is.close();
sock.close();
}
catch (IOException e)
{
break;
}
}
}
}
考慮添加Content-Length
標頭以指定響應的大小,以便瀏覽器知道要讀取的內容。
程序死機的原因是它等待客戶端關閉連接(eof后read返回的值小於0)。 您應該閱讀以下內容,直到從客戶端收到雙精度[cr] [lf],這才是http標頭結尾的標志
String httpResponse = "";
這不是有效的HTTP響應。 您的瀏覽器正在等待正確的響應。 發送一個。
從我看來,您在回答客戶的請求之前先關閉插座
另外,我測試了您的代碼,雖然周期永遠不會結束
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.