Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中,是否有任何方法可以通过TCP/IP连接到其他主机而不使用;while(true)“;_Java_Sockets_Io - Fatal编程技术网

在java中,是否有任何方法可以通过TCP/IP连接到其他主机而不使用;while(true)“;

在java中,是否有任何方法可以通过TCP/IP连接到其他主机而不使用;while(true)“;,java,sockets,io,Java,Sockets,Io,大家好。有个问题,我想了很久。 我可以通过“套接字”连接其他主机。我使用了“socketServer.accept()”。当有人打电话给我时,我能知道。这是代码 while (this.connState != 0) { Socket client = null; try { client = this.serverSocket.accept(); } catch (IOException e) {

大家好。有个问题,我想了很久。 我可以通过“套接字”连接其他主机。我使用了“socketServer.accept()”。当有人打电话给我时,我能知道。这是代码

while (this.connState != 0) {
        Socket client = null;
        try {
            client = this.serverSocket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        }
}
然后我可以得到“流”,并得到我的数据

但我不想那样做


我想告诉操作系统,当我得到数据时,我将做什么。如果可能的话,我不必每次都检查插座。我可以这样做吗?是否有我可以使用的接口或事件?

您可以删除
while()
循环;在这种情况下,服务器将只接受一个连接并终止

这不是一个“忙循环”。
ServerSocket.accept()
将阻塞,直到建立连接为止

正如在另一个答案中所解释的,您可以使用NIO。另一个选项是在“”中解释的Akka(不,我不是在这里复制和粘贴Akka文档中的约200行代码)


虽然Akka的设置看起来非常昂贵,但奖励是一个强大的系统,可以对传入的连接进行切分,将它们转换为消息,通过参与者进行路由,然后返回结果或将消息传递给其他参与者。

幸运的是,Java NIO支持这一点:

下面是一个不使用(容易出错)循环的有用示例:

import java.io.IOException;
导入java.net.InetSocketAddress;
导入java.net.SocketAddress;
导入java.nio.ByteBuffer;
导入java.nio.channels.AsynchronousServerSocketChannel;
导入java.nio.channels.AsynchronousSocketChannel;
导入java.nio.channels.CompletionHandler;
导入java.nio.charset.charset;
公共班机{
公共静态void main(字符串[]args)引发异常{
AsynchronousServerSocketChannel服务器=AsynchronousServerSocketChannel
.open();/*ww w.j av a 2s.c om*/
String host=“localhost”;
int端口=8989;
InetSocketAddress sAddr=新的InetSocketAddress(主机、端口);
服务器绑定(sAddr);
System.out.format(“服务器正在侦听%s%n”,sAddr);
附件附加=新附件();
attach.server=服务器;
accept(attach,newconnectionhandler());
Thread.currentThread().join();
}
}
班级附件{
异步服务器socketchannel服务器;
异步socketchannel客户端;
ByteBuffer缓冲器;
SocketAddress clientAddr;
布尔isRead;
}
类ConnectionHandler实现

CompletionHandler

您的问题不是很清楚,但我想知道您是否在谈论一种反应式编程方法

使用类似这样的工具,您可以编写一个处理程序,系统在接收数据时调用该处理程序。它处理很多底层细节,比如线程和套接字。您只需在收到数据时写入


Akka的网络功能是高度可扩展的,基于Java的“新”I/O(NIO)库,可以在非阻塞、基于选择器的模式下使用。(Akka使用构建在这些较低级别NIO包上的,用于远程消息发送功能;我认为Akka的网络包也可能使用Netty。)

您的代码示例是一个无限循环。哪一行代码会将
this.connState
设置为零以外的值?我想你真正想说的是,“如何避免套接字的阻塞性。接受?”不,这根本不是这个问题的重复。。。。甚至连我都做不到?这很值得怀疑。。。除非它有一个到异步NIO的映射或类似的东西。这似乎是我想要的。谢谢。非常好-在这种情况下,请“接受”答案,以便董事会能够正确分类。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
public class Main {
  public static void main(String[] args) throws Exception {
    AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel
        .open();/*  ww w . j av a 2s. c om*/
    String host = "localhost";
    int port = 8989;
    InetSocketAddress sAddr = new InetSocketAddress(host, port);
    server.bind(sAddr);
    System.out.format("Server is listening at %s%n", sAddr);
    Attachment attach = new Attachment();
    attach.server = server;
    server.accept(attach, new ConnectionHandler());
    Thread.currentThread().join();
  }
}
class Attachment {
  AsynchronousServerSocketChannel server;
  AsynchronousSocketChannel client;
  ByteBuffer buffer;
  SocketAddress clientAddr;
  boolean isRead;
}

class ConnectionHandler implements
    CompletionHandler<AsynchronousSocketChannel, Attachment> {
  @Override
  public void completed(AsynchronousSocketChannel client, Attachment attach) {
    try {
      SocketAddress clientAddr = client.getRemoteAddress();
      System.out.format("Accepted a  connection from  %s%n", clientAddr);
      attach.server.accept(attach, this);
      ReadWriteHandler rwHandler = new ReadWriteHandler();
      Attachment newAttach = new Attachment();
      newAttach.server = attach.server;
      newAttach.client = client;
      newAttach.buffer = ByteBuffer.allocate(2048);
      newAttach.isRead = true;
      newAttach.clientAddr = clientAddr;
      client.read(newAttach.buffer, newAttach, rwHandler);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void failed(Throwable e, Attachment attach) {
    System.out.println("Failed to accept a  connection.");
    e.printStackTrace();
  }
}

class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {
  @Override
  public void completed(Integer result, Attachment attach) {
    if (result == -1) {
      try {
        attach.client.close();
        System.out.format("Stopped   listening to the   client %s%n",
            attach.clientAddr);
      } catch (IOException ex) {
        ex.printStackTrace();
      }
      return;
    }

    if (attach.isRead) {
      attach.buffer.flip();
      int limits = attach.buffer.limit();
      byte bytes[] = new byte[limits];
      attach.buffer.get(bytes, 0, limits);
      Charset cs = Charset.forName("UTF-8");
      String msg = new String(bytes, cs);
      System.out.format("Client at  %s  says: %s%n", attach.clientAddr,
          msg);
      attach.isRead = false; // It is a write
      attach.buffer.rewind();

    } else {
      // Write to the client
      attach.client.write(attach.buffer, attach, this);
      attach.isRead = true;
      attach.buffer.clear();
      attach.client.read(attach.buffer, attach, this);
    }
  }

  @Override
  public void failed(Throwable e, Attachment attach) {
    e.printStackTrace();
  }
}