【问题标题】:retrieve the exact connection - tcp socket - channel - goroutine检索确切的连接 - tcp 套接字 - 通道 - goroutine
【发布时间】:2017-01-18 02:44:39
【问题描述】:

我在学习Golang几天,所以我不清楚如何在函数内检索正确的连接“conn”

func 进程消息

对于相关消息“msg”

谢谢!

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\n", 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('\n')
    msgchan <- o
  }

}

在函数func handleConnection中我有连接,但是..如何将连接转发到通道“msgchan”以及消息“

瓦莱里亚诺·科苏

【问题讨论】:

    标签: sockets go tcp channel goroutine


    【解决方案1】:

    只提供适合目的类型的频道

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

    【讨论】:

    • 我需要的解决方案,非常感谢!伟大的! ciao Uvelichitel
    猜你喜欢
    • 2014-04-08
    • 2011-08-31
    • 2023-03-21
    • 2020-07-04
    • 2020-12-20
    • 1970-01-01
    • 2015-03-05
    • 2012-02-28
    相关资源
    最近更新 更多