简体   繁体   English

如何将套接字连接从一个套接字通道转移到另一个?

[英]How do you transfer a socket connection from one socketchannel to another?

I have a ServerSocketChannel and once this channel accepts a connection I want to "transfer" or "pass" it to a SocketChannel.我有一个 ServerSocketChannel,一旦这个通道接受了一个连接,我想将它“传输”或“传递”到一个 SocketChannel。 I have tried, once I have accepted the connection, to simply do a socketchannel.bind(ServerSocketChannel.socket.getLocalSocketAddress) but I get an exception that says "Address already in use".我尝试过,一旦我接受了连接,就简单地做一个socketchannel.bind(ServerSocketChannel.socket.getLocalSocketAddress)但我得到一个异常,上面写着“地址已在使用中”。 Which makes sense so I have tried to save the socket address in a variable, close the ServerSocketChannel, and then attempt to bind it with the variable but it still complains about already being in use.这是有道理的,所以我尝试将套接字地址保存在变量中,关闭 ServerSocketChannel,然后尝试将其与变量绑定,但它仍然抱怨已经在使用中。

//Accept the connection
ServerSocketChannel.accept();

//Save the address and close the connection
address = ServerSocketChannel.socket().getLocalSocketAddress();
ServerSocketChannel.close();

//Bind the address to another channel
SocketChannel.bind(address);//Here is where I get the exception

This is how my solution looks right now(except for the variable names but you get the idea).这就是我的解决方案现在的样子(除了变量名,但你明白了)。 The reason I can't just accept it with that channel is because it's used for another purpose once this connection has been established, so I need to have dedicated ServerSocketChannel opened just for accepting connections which are then passed to the SocketChannel.我不能只用那个通道接受它的原因是因为一旦建立了这个连接它就被用于另一个目的,所以我需要打开专用的 ServerSocketChannel 来接受然后传递给 SocketChannel 的连接。

I just solved my problem.我刚刚解决了我的问题。 I overlooked something simple and tried a longer way instead.我忽略了一些简单的事情,而是尝试了更长的方法。 SocketChannel = ServerSocketChannel.accept(); Is what I was looking for all along.是我一直在寻找的。

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

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