Akka create two Tcp Connections with the same port

时间:2016-07-11 19:11:14

标签: scala tcp akka

I'm trying to create two tcp connections that are bound to the same port. I'm getting an error saying that the java.net.BindException: Address already in use. This makes sense since they are both using 18333 as a port, but there must be some way to have two connections on a port that have unique hosts. I'm following along with the guide in the akka tcp manual. How can I make this work? The protocol says that connections need to be created on 18333, however if I can only have one peer at a time it makes the p2p portion of the protocol useless.

Here is the code:

val probe1 = TestProbe()
val probe2 = TestProbe()
val client1 = system.actorOf(Client.props(TestNet3, probe1.ref))
val client2 = system.actorOf(Client.props(TestNet3, probe2.ref))

val local = new InetSocketAddress(18333)

val remote1 = new InetSocketAddress("testnet-seed.bitcoin.petertodd.org", 18333)

client1 ! Tcp.Connect(remote1,Some(local))
probe1.expectMsgType[Tcp.Connected]

val remote2 = new InetSocketAddress("testnet-seed.bluematt.me", 18333)
client2 ! Tcp.Connect(remote2,Some(local))
probe2.expectMsgType[Tcp.Connected]


client1 ! Tcp.Abort
client2 ! Tcp.Abort

2 个答案:

答案 0 :(得分:1)

您需要查找如何为套接字设置akka set SO_REUSEADDR。这必须在Tcp.Connect中发生,因此您可能必须将类似SO.ReuseAddr(true)的内容作为套接字选项传递。

OP代码根据答案解决他的问题:

val options = List(Inet.SO.ReuseAddress(true))
client1 ! Tcp.Connect(remote1, Some(local1), options)

Inet.SO documentation

答案 1 :(得分:0)

You don't provide enough context for the environment you are trying to run in. When it says "the connections need to be created on 18333", are they talking about the source of the connection or the destination? It would make more sense to be the destination. Your code specifies the source address, when it shouldn't care what the source address is; you only care about the destination address.