简体   繁体   English

Java上的客户端套接字

[英]Client Socket on Java

In most Java client/server examles they use ServerSocket.accept() method to receive messages from the client. 在大多数Java客户端/服务器示例中,它们使用ServerSocket.accept()方法接收来自客户端的消息。 This method blocks the thread. 此方法阻塞线程。 This looks good becouse server does not do useless work and can answer immediately. 这看起来不错,因为服务器不会做无用的工作并且可以立即答复。 But on the client side they use infinite loop like this: 但是在客户端,他们使用无限循环,如下所示:

BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
    String cominginText = "";
    try
    {
        cominginText = in.readLine ();
        System.out.println (cominginText);
    }
    catch (IOException e)
    {
        //error ("System: " + "Connection to server lost!");
        System.exit (1);
        break;
    }
}

This looks bad because in my mind client does useless work. 这看起来很糟糕,因为在我看来客户没有做任何工作。 Is there some way to receive a message on the client side without doing useless work and immediately like on server side (may be should use listeners?) 是否有某种方法可以在客户端接收消息而无需做无用的工作,而立即像在服务器端一样(可能应该使用侦听器?)

"What do you mean by useless work? – Braj 31 mins ago " “您所说的无用工作是什么意思?– Braj 31分钟前”

for example checking in loop is button pressed (we should use listener) 例如检查循环是否按下按钮(我们应该使用监听器)

while (!button.isPressed() ) { } is bad way. while (!button.isPressed() ) { }是不好的方法。

in.readLine() blocks. in.readLine()块。 The loop wont continue until a String returns 直到字符串返回,循环才会继续

There is no 'useless work' here, as the socket is in blocking mode, but there is: 由于套接字处于阻塞模式,因此这里没有“无用的工作”,但是有:

  1. A pointless initialization of 'comingText'. “ comingText”的无意义初始化。
  2. A failure to check it for null, so it will spin mindlessly at EOS. 无法检查它是否为空,因此它将在EOS上无意识地旋转。
  3. An incorrect handling of IOExceptions: not all of them are fatal, eg SocketTimeoutException, and none of them should cause an immediate System.exit(). IOExceptions的错误处理:并非所有致命错误,例如SocketTimeoutException,并且它们都不应该立即导致System.exit()。
  4. The line read is thrown away, which is an application protocol error. 读取的行被丢弃,这是应用程序协议错误。

So it is definitely wrong. 因此,这绝对是错误的。

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

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