检索确切的连接-TCP套接字-通道-goroutine

I am learning Golang by few days, so it's not clear to me, how to retrieve the right connection "conn" inside the function

func processMessages

for the relative message "msg"

Thanks!

package main

import ( 
  "fmt"
  "log"
  "net" 
  "os"
  "encoding/json"
  "time"
  "bufio"
)

type Packet struct {
  Payload Payload   `json:"payload"`
}

type Payload struct {
  Data string       `json:"data"`
}



func main() {

  if len(os.Args) != 2 {
    fmt.Fprintf(os.Stderr, "Usage: %s hostname
", os.Args[0])
    fmt.Println("Usage: ", os.Args[0], "port number")
    os.Exit(1)
  }

  msgchan := make(chan string)
  go processMessages(msgchan)

  addr := ":" + os.Args[1]

  ln, err := net.Listen("tcp", addr)
  if err != nil {
    fmt.Println(err)
    //log.Fatal(err)
  }

  fmt.Println("Server listening at ", addr)

  for {

    conn, err := ln.Accept()
    if err != nil {
      log.Println(err)
      continue
    }

    /* FIRST GOROUTINE */
    go handleConnection(conn, msgchan)
  }

}

func processMessages(msgchan <-chan string) {

  for msg := range msgchan {

    /*

    .. here the problem.. how I can know here the 'conn' the relative connection for this message???

    */

    if len(msg)>0 {

      packet := &Packet{}
      err := json.Unmarshal([]byte(msg), packet)
      if err != nil {
        log.Fatalln("Error xxx: ", err)
      } else {

        if len(packet.Payload.Data) > 0 {

          fmt.Println( len(packet.Payload.Data) )

        }
      }
    }

  }
}

func closeConnection(c net.Conn) {
  c.Close()
}

func handleConnection(c net.Conn, msgchan chan<- string) {

  for {
    inputReader := bufio.NewReader(c)
    o, _ := inputReader.ReadString('
')
    msgchan <- o
  }

}

inside the function func handleConnection I have the connection, but.. how to forward the connection to the channel "msgchan" together with the message "<- o" ???

Valeriano Cossu

Just provide channel of type suitable for purpose

type Msg struct {
    Msg  string
    Conn *net.Conn
}

type MsgChan chan Msg

func handleConnection(c net.Conn, msgchan MsgChan) {
//...
    msgchan <- Msg{Msg: o, Conn: &c}
//...
}

func processMessages(msgchan <-chan Msg) {
  for msg := range msgchan {
       m := msg.Msg
       conn := nsg.Conn
//...
}