简体   繁体   English

无法从Java中的ServerSocket读取数据

[英]Cannot read data from ServerSocket in Java

The code below is in server side. 下面的代码在服务器端。 It could handle client request and then show the client input in my console. 它可以处理客户端请求,然后在我的控制台中显示客户端输入。

Yet, the problem appears... 然而,问题出现了……

The console shows the string "hello from clientA" successfully. 控制台成功显示字符串“来自clientA的hello”。 But, I cannot use "if" to analyze this word. 但是,我不能使用“ if”来分析这个词。

My objective is to show "ok" in console if it is a request from "clientA". 我的目标是在控制台中显示“ ok”(如果这是来自“ clientA”的请求)。 To conclude that, the program does not reach "System.out.println("ok")" even though it matches the condition. 可以断定,即使符合条件,程序也不会到达“ System.out.println(“ ok”)“。

Please help me )...( 请帮我 )...(

Thanks. 谢谢。

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;
     }
  }

Do not use == to compare strings, use String#equals() method so 不要使用==比较字符串,请使用String#equals()方法,这样

if(obtain=="hello from clientA")

should be replaced by 应该替换为

if("hello from clientA".equals(obtain))

hope this helps. 希望这可以帮助。

Change that if condition to this : 如果条件更改为此:

if(obtain.equals("hello from clientA"))
    {
        System.out.println("ok");
    }

== operator is checking the reference of the value and not the actual value. ==操作员正在检查值的参考值,而不是实际值。 Whereas String#equals compare the value of object and return TRUE or FALSE accordingly. String#equals比较对象的值并相应地返回TRUE或FALSE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM