0

我正在尝试“编写一个作为 TCP 服务器的 Java 程序,它向浏览器返回 HTTP 响应,显示客户端的 IP 地址及其连接到服务器的次数”

目前我认为正在发生的事情。我正在创建一个服务器并监听请求的端口(作为参数输入),然后填充一个字节数组并将该数组转换为字符串。我希望此时只看到请求。

我的问题是,如果我确实尝试通过访问我的网络浏览器并键入“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; 
        }
}
}
}
4

4 回答 4

0

考虑添加一个Content-Length标头来指定响应的大小,以便浏览器知道要读取多少。

于 2012-05-16T19:29:01.357 回答
0

您的程序冻结的原因是它等待客户端关闭连接(读取在 eof 之后返回一个 <0 的值)。您应该阅读,直到您从客户端收到双 [cr][lf],这就是 http 标头结束的标志

于 2012-05-16T19:36:33.347 回答
0
String httpResponse = "";

这不是有效的 HTTP 响应。您的浏览器正在等待正确的响应。发一个。

于 2012-05-17T03:12:34.883 回答
-1

from what i see, you closed the socket before answering the client's request

also, i tested your code, and that while cycle never ends

于 2012-05-16T19:24:20.387 回答