java - 这种情况下socket的accept方法会阻塞吗

标签 java sockets threadpool

只是一个简短而甜蜜的故事。我正在尝试制作一个聊天客户端,因此我有一个线程池来管理服务器上的套接字连接。如果我使用:

    while(true) {
        thrdPool.execute(new ServChatSocket(servSocket.accept(), InOutMan));
    }

这是否会阻止 ServChatSocket 被创建并添加到池中,直到它收到连接,向池中添加一个奇怪的损坏的 ServChatSocket 并产生意外结果,或者抛出某种重复错误,直到收到入站连接?

我是否应该在 while block 中使用 if 语句来检查在传递到 thrdPool 之前是否有对象准备连接?像这样的东西:

    while(true) {
        if(s = servSocket.accept()) {
            thrdPool.execute(new ServChatSocket(s, InOutMan));
        }
    }

除了防止上述错误(如果有的话)之外,这是否会被认为是更好、更干净的代码?

最佳答案

Will this block ServChatSocket's from being created and added to the pool until it receives a connection

是的。

add a weird broken ServChatSocket to the pool with unexpected results

没有。

or throw some kind of repeated error until it receives an inbound connection?

没有。

Should I use an if statement in the while block to check if there is an object ready to connect before passing to the thrdPool?

没有。 ServerSocket.accept() 永远不会返回 null。

关于java - 这种情况下socket的accept方法会阻塞吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519017/

相关文章:

java - 应该在列表本身还是在锁定对象上进行同步?

java - 如何获取Android中textView的最大长度?

c# - PHP 到 C# - 套接字 - 文件随机损坏

python - 尝试为 python 中的并行 API 调用添加节流控制

java - 如何使用 VIM/GVIM 调试 Java 应用程序?

java - 添加新组件时更新(和扩展)对话框

java - 套接字还是 HTTP POST 请求?

c++ - Windows 2012 R2 closesocket() 卡在监听套接字上

.net - 线程返回线程池后ExecutionContext是否被清除?

java - 线程状态监视器。我该如何调试?是什么原因造成的?