gpt4 book ai didi

java - 与套接字输入流比较时的字符串相等问题

转载 作者:行者123 更新时间:2023-12-01 10:19:53 25 4
gpt4 key购买 nike

编辑:

抱歉没有说清楚,我发现这个问题与枚举无关:

对于我的情况,枚举如下所示,我使用 contains 方法来检查字符串值是否属于:

    public static enum RequestMethod {
HEAD, GET, POST;

public static boolean contains(String test) {

for (RequestMethod m : RequestMethod.values()) {
System.out.println("Testing: method |"+m.name()+"|, input |"+test+"|");
if (m.name().equals(test.trim())) {
return true;
}
}
return false;
}
}

服务器端测试代码为:

Socket clientSock;
......

InputStream clientInput = clientSock.getInputStream()
BufferedReader inStream = new BufferedReader(new InputStreamReader(
clientInput));

String buffer = inStream.readLine();
String[] reqLine = buffer.split(" ");

System.out.println("test GET---");
System.out.println(Request.RequestMethod.contains("GET"));
System.out.println("test GET---");

System.out.println("test reqLine[0]---");
System.out.println(Request.RequestMethod.contains(reqLine[0]));
System.out.println("test reqLine[0]---");

System.out.println("reqLine[0] equals GET? " + reqLine[0].equals("GET"));

当客户端通过套接字向服务器发送“GET/index.html HTTP/1.0”时,输出为:

Client send: GET /index.html HTTP/1.0
test GET---
Testing: method |HEAD|, input |GET|
Testing: method |GET|, input |GET|
true
test GET---

test reqLine[0]---
Testing: method |HEAD|, input |GET|
Testing: method |GET|, input |GET|
Testing: method |POST|, input |GET|
false
test reqLine[0]---

reqLine[0] equals GET? false

reqLine[0] 打印为“GET”,但它们被认为不相等,这会导致问题。

于是我去检查客户端(提供给我的)是如何将数据放入socket的,我发现:

Socket sock;
......
DataOutputStream outStream = new DataOutputStream(sock.getOutputStream());
outStream.writeChars(buffer); // this line causes issue
outStream.writeChar('\n');
outStream.flush();

当我将 writeChars 更改为 writeBytes 时,服务器端的字符串 equals 按预期工作。

test GET---
Testing: method |HEAD|, input |GET|
Testing: method |GET|, input |GET|
true
test GET---

test reqLine[0]---
Testing: method |HEAD|, input |GET|
Testing: method |GET|, input |GET|
true
test reqLine[0]---

GET equals reqLine[0]? true

当我脑子一片模糊时,我不应该发布这个问题。

那么我想我的问题应该改为:为什么writeCharswriteBytes发送的字符串打印结果相同但不相等?

是不是因为writeChar(writeChars)将每个char写成2个字节?

writeChar

public final void writeChar(int v) throws IOException

Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2.

最佳答案

上面的代码没有问题。我定义了自己的 ENUM 选择。

public enum Choice {
GOOD, BAD, UGLY}

然后用

测试了上面的方法
contains("BAD") -> This returned true.
contains("BAD1") -> This returned false

关于java - 与套接字输入流比较时的字符串相等问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35667170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com