Skip to content

Commit

Permalink
Fixed dangling goroutine for rx() avoiding reading from a dead TCP so…
Browse files Browse the repository at this point in the history
…cket.
  • Loading branch information
hdhauk committed Mar 16, 2017
1 parent f5c9424 commit 71b0b45
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ _testmain.go
vendor/
/.project

server
client
sc-server
sc-client
17 changes: 13 additions & 4 deletions sc-server/sc-server.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func socketHandler(c net.Conn) {
incommingReq := make(chan msg.ClientReq)
outgoingResp := make(chan msg.ServerResp)
closeConnCh := make(chan struct{})
go rx(c, incommingReq)
go rx(c, incommingReq, closeConnCh)
go tx(c, outgoingResp, closeConnCh)

var username string
Expand All @@ -100,12 +100,19 @@ func socketHandler(c net.Conn) {
}
}

func rx(c net.Conn, out chan msg.ClientReq) {
func rx(c net.Conn, out chan msg.ClientReq, closeConnCh chan struct{}) {
emptyReq := msg.ClientReq{}
remoteAddr := c.RemoteAddr().String()
for {
// Decode incomming msg
var req msg.ClientReq
json.NewDecoder(c).Decode(&req)
err := json.NewDecoder(c).Decode(&req)
if err != nil {
log.Printf("[ERROR] Decoding request: %s\n", err.Error())
close(closeConnCh)
log.Printf("[INFO] Stopping rx for client %v\n", remoteAddr)
return
}
if req == emptyReq {
continue
}
Expand All @@ -114,14 +121,16 @@ func rx(c net.Conn, out chan msg.ClientReq) {
}

func tx(c net.Conn, out chan msg.ServerResp, closeConnCh chan struct{}) {
remoteAddr := c.RemoteAddr().String()
for {
select {
case resp := <-out:
// fmt.Printf("Sending %+v\n", resp)
json.NewEncoder(c).Encode(&resp)
case <-closeConnCh:
log.Printf("[INFO] Closing connection to %+v\n", c.RemoteAddr())
log.Printf("[INFO] Closing connection to %+v\n", remoteAddr)
c.Close()
log.Printf("[INFO] Stopping tx for client %v\n", remoteAddr)
return
}
}
Expand Down

0 comments on commit 71b0b45

Please sign in to comment.