douyi7283 2016-09-09 21:52
浏览 29

检索确切的连接-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

  • 写回答

1条回答 默认 最新

  • donglu4159 2016-09-09 22:17
    关注

    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
    //...
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试