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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP