簡體   English   中英

如何將套接字連接從一個套接字通道轉移到另一個?

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

我有一個 ServerSocketChannel,一旦這個通道接受了一個連接,我想將它“傳輸”或“傳遞”到一個 SocketChannel。 我嘗試過,一旦我接受了連接,就簡單地做一個socketchannel.bind(ServerSocketChannel.socket.getLocalSocketAddress)但我得到一個異常,上面寫着“地址已在使用中”。 這是有道理的,所以我嘗試將套接字地址保存在變量中,關閉 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

這就是我的解決方案現在的樣子(除了變量名,但你明白了)。 我不能只用那個通道接受它的原因是因為一旦建立了這個連接它就被用於另一個目的,所以我需要打開專用的 ServerSocketChannel 來接受然后傳遞給 SocketChannel 的連接。

我剛剛解決了我的問題。 我忽略了一些簡單的事情,而是嘗試了更長的方法。 SocketChannel = ServerSocketChannel.accept(); 是我一直在尋找的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM