下面的代码是在服务器端。它可以处理客户端请求,然后在我的控制台中显示客户端输入。
然而,问题出现了......
控制台成功显示字符串“hello from clientA”。但是,我不能用“if”来分析这个词。
我的目标是如果是来自“clientA”的请求,则在控制台中显示“ok”。综上所述,即使符合条件,程序也不会到达“System.out.println("ok")”。
请帮助我)...(
谢谢。
while(true)
{
Socket server = null;
try
{
server = serverSocket.accept();
DataInputStream in =
new DataInputStream(server.getInputStream());
obtain=in.readUTF();
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("server say hello to you");
System.out.println(obtain);//the console show "hello from clientA" exactly
if(obtain=="hello from clientA")
{
System.out.println("ok");
}
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Again");
try {
serverSocket.setSoTimeout(20000);
} catch (IOException e) {
}
}
catch(Exception b)
{
break;
}
}
最佳答案
不要使用==
来比较字符串,而是使用String#equals()
方法
if(obtain=="hello from clientA")
应替换为
if("hello from clientA".equals(obtain))
希望这有帮助。
关于java - 无法从Java中的ServerSocket读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24504029/