Reputation: 406
I'm looking to implement a TCP server in go, which should be able to receive data from one client and send it to another. What will be the correct way to achieve that? I tried the following code:
astSrc := *addr + ":" + strconv.Itoa(*astPort)
astListener, _ := net.Listen("tcp", astSrc)
fmt.Printf("Listening on %s for Client Connections.\n", astSrc)
defer astListener.Close()
pmsSrc := *addr + ":" + strconv.Itoa(*pmsPort)
pmsListener, _ := net.Listen("tcp", pmsSrc)
fmt.Printf("Listening on %s for DB Connections.\n", pmsSrc)
defer pmsListener.Close()
for {
pmsConn, pmsErr := pmsListener.Accept()
if pmsErr != nil {
fmt.Printf("Some connection error: %s\n", pmsErr)
}
go handlePMSConnection(pmsConn)
astConn, astErr := astListener.Accept()
if astErr != nil {
fmt.Printf("Some connection error: %s\n", astErr)
}
go handleAstConnection(astConn, pmsConn)
}
I was thinking to use 2 different ports for each client (astSrc - which is an short time connection and pmsSrc - permanent connection) and make 2 listeners for each of them. I want to be able to receive a message from Client-1 connected to the astSrc port, and pass it on Client-2 (pmsSrc port). This code is working so far, but if the client-1 is discconected and then connected back - the server is not accepting any message anymore. I don't know if it's correct to handle both connections in the same loop, i think that's the problem, but if I'm taking out of the loop one connection then that connection will be unreachable. Could you please point me into right direction?
Upvotes: 0
Views: 817
Reputation: 598
Problem looks to be that you need a pms connection for every ast connection your getting, inserting your acceptanse of ast connections in a loop would probably solve your immediate problem, like this
for {
pmsConn, pmsErr := pmsListener.Accept()
if pmsErr != nil {
fmt.Printf("Some connection error: %s\n", pmsErr)
}
go handlePMSConnection(pmsConn)
for {
astConn, astErr := astListener.Accept()
if astErr != nil {
fmt.Printf("Some connection error: %s\n", astErr)
}
go handleAstConnection(astConn, pmsConn)
}
}
But problems would arise if you lost the pms connection, and what would happen if you get multiple ast connections. And you would need to connect the pms connection before the ast connection.
Upvotes: 1