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