此程序的主要目的是能够从浏览器读取请求行并打印出该特定请求行的前两个单词。然而,当涉及到编译程序时,我一次又一次地得到相同的错误,我不确定是什么问题。这是我写的代码示例:
import java.io.*;
import java.net.*;
import java.util.*;
public class UselessHTTPServer05 {
public static void main(String args[]) throws Exception {
int port = Integer.parseInt(args[0]);
ServerSocket serverSock = new ServerSocket(port);
while (true) {
Socket conn = serverSock.accept();
Scanner scanin = new Scanner(conn.getInputStream());
String line = null;
int nlines=0;
String[] stringArray = new String[32];
while (true) {
line = scanin.nextLine();
if (line.length() == 0)
break;
stringArray [nlines] = line;
nlines = nlines + 1;
//System.out.println("line "+nlines+": " + line);
for (int i = 0; i < nlines; i++)
System.out.println("Line: " + i + " " + stringArray[i]);
Scanner scans = new Scanner(stringArray);
String command = scans.next();
String resource = scans.next();
System.out.println("Command: " + command);
System.out.println("Resource " + resource);
}
String reply="HTTP/1.0 404 Not Found\r\n" +
"Connection: close\r\n" +
"Content-Type: text/html\r\n" +
"\r\n" +
"<h1>Sorry, work in progress</h1>\r\n";
OutputStream outs = conn.getOutputStream();
outs.write(reply.getBytes());
conn.close();
}
}
}
错误与代码的扫描程序部分有关,我已经声明了一个名为扫描程序的扫描程序&#34;扫描&#34;并编写了代码来执行扫描请求行的任务,并删除存储在&#34;命令&#34;中的前两个单词。和&#34;资源&#34;。
答案 0 :(得分:2)
String[] stringArray = new String[32];
...
Scanner scans = new Scanner(stringArray);
stringArray
的类型为String[]
,请访问Scanner
API以确认没有此类构造函数。
答案 1 :(得分:0)
。 String []没有构造函数。您需要以不同的方式执行此操作,例如,
编写自己的扫描器类,在其中编写自己的扫描器构造函数,并使用Scanner类扩展它。
或者您将String数组更改为其他类型(可能是Inputstream)
第三种方式:你可以做到,我不知道这是用于java还是只用C,你可以用扫描器创建一个数组,你可以为字符串数组中的每个字符串调用构造函数PseudoCode
foreach String in StringArray
ArrayofScanners[i] = new Scanner(String);
i++;
答案 2 :(得分:0)
找到解决方案!我创建了一个String变量来存储服务器的第一个请求行。我还宣布了一个新的Scanner来读取请求行,exaple如下所示:
String string = stringArray[0] //this will read the first request line
Scanner scans = new Scanner(string) //this will scan through the request line stored in string
下一步是将请求行的前两个单词存储到两个名为Command和Resource的String变量中:
String Command = scans.next();
String Resource = scans.next();
最后,只需打印出两个单词:
System.out.println("Command: " + Command);
System.out.println("Resource: " + Resource);
在实现上述代码之前,请求行包括:
Line: 0 GET /file.html HTTP/1.1
实现上述代码后,前两个单词将被打印并存储到Command and Resource:
中Command: GET
Resource: /file.html
感谢所有回复帖子的人,真的帮到了很多!