我正在从文件中读取 json 数据并使用 gob 编码将其发送到远程服务器,但我对我的代码不满意,我尝试了几种方法来获得更通用的功能,但我失败了,唯一的方法我的代码对每种类型都具有相同的功能。我尝试使用 switch 类型,但以同样的方式需要重复代码以解组和编码 gob 数据拜托,有人可以帮助我了解如何改进吗?两种类型:type Data1 struct{ID intMessage string}type Data2 struct{ Serial int Height float64 Loss float64 Temp float64 Oil float64}Data1 类型的函数func SenderData1(address string, buff *filebuffer.Buffer) { var conn net.Conn var err error var line string var obj Data1 for { line, err = buff.Pop() if err != nil { log.Critical("Error Poping:", err.Error()) continue } if len(line) == 0 { time.Sleep(1 * time.Second) continue } if err := json.Unmarshal([]byte(line), &obj); err != nil { log.Critical("Error Unmarshaling:", err.Error()) continue } for { log.Info("Trying to connect with Server...") conn, err = net.Dial(PROTO, address) // If err try to connect again if err != nil { log.Error("Error connecting:", err.Error()) time.Sleep(1 * time.Second) continue } // If connected break the loop break } log.Debug("Sending ", obj, " to:", address) encoder := gob.NewEncoder(conn) err := encoder.Encode(obj) if err != nil { log.Critical("Error Encoding Gob:", err.Error()) } // Timer between every sending, ie. Reading from buffer time.Sleep(300 * time.Millisecond) conn.Close() }}
1 回答
- 1 回答
- 0 关注
- 154 浏览
添加回答
举报
0/150
提交
取消