ServerSocket被线程从控制台寻求输入阻止 [英] ServerSocket blocked by thread seeking input from console

查看:96
本文介绍了ServerSocket被线程从控制台寻求输入阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以让我深入了解ServerSocket构造函数为何从不返回新线程吗? (我从未见过将"Opened"消息打印到控制台.)似乎主线程通过太快地进入readLine来阻止服务器套接字线程运行:

Can anyone give me insight into why the ServerSocket constructor never returns in the new thread? (I never see the "Opened" message printed to the console.) It seems the main thread prevents the server socket thread from running by entering into readLine too quickly:

public class Main
{
   public static void main(String[] args) throws IOException
   {
      new Thread(new SocketOpener()).start();

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String inLine = br.readLine();
      System.out.println(inLine);
   }
}

public class SocketOpener implements Runnable
{

   public void run()
   {
      try
      {
         System.out.println("Opening...");
         ServerSocket socket = new ServerSocket(4444);
         System.out.println("Opened");
      }
      catch (IOException ex)
      {
         System.out.println("IO Error");
      }
   }

}

推荐答案

从System.in读取会导致很多问题: 在某些情况下,您不能:

Reading from System.in causes a lot of problems: Under some circumstances you can't:

  1. 创建一个临时文件(因为2)
  2. 阅读您的机器的Inet4Adress
  3. 加载DLL

我在Windows Server 2003和更早版本中遇到了一些此类问题.发生这种情况是由于Win32-API和Java-VM中存在一些错误.

I've encountert some of this Problems with Windows Server 2003 and older. This happens because of some Bugs in the Win32-API ans Java-VM.

但是可能会有一个简单的解决方法:

But there may be an easy workarround:

如果System.in.availiable()返回的值大于0,则仅调用System.in.read().

Only call System.in.read(), if System.in.availiable() returns a value larger than 0.

这篇关于ServerSocket被线程从控制台寻求输入阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆