donglv1831 2014-01-26 21:22
浏览 59
已采纳

Go语言中的结构无法使用json编码获取正确的数据

//package cluster
package main

import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"math/rand"
"net"
"os"
"strconv"
"time"
//"bytes"
)

const (
BROADCAST = -1
 )

var outbox, inbox chan *Envelope
var pids [10]int
var ips [10]string

type Envelope struct {
Pid   int
MsgId int64
Msg   interface{}
}

type Server interface {
Pid() int
Peers() []int
Outbox() chan *Envelope
Inbox() chan *Envelope
}

/*
func (envelope Envelope) Pid() int {
return envelope.MsgId
}
*/
var server Envelope

func (envelope Envelope) Peers() []int {
return nil //pids
}

func (envelope Envelope) Outbox() chan *Envelope {
return outbox
}

func (envelope Envelope) Inbox() chan *Envelope {
return inbox
}

func server_() {
// listen on a port
ln, err := net.Listen("tcp", ":9999")
//time.Sleep(time.Second * 2)
if err != nil {
    fmt.Println(err)
    return
}
for {
    c, err := ln.Accept()
    if err != nil {
        fmt.Println(err)
        continue
    } else {
        fmt.Println("handle")
        go handleServerConnection(c)
    }
} 
}

func handleServerConnection(c net.Conn) {
// receive the message
var msg Envelope
var b []byte
//  for{
c.Read(b)
/*
    if b == nil{
        continue
    }else{
        break
    }
*/
//  }

fmt.Println(b)
err := json.Unmarshal(b, &msg)
if err != nil { //ERORR !!!!
    fmt.Println(err)
} else {
    fmt.Println("Received : %+v", msg)
}
c.Close()
}

func client() {
// connect to the server
for msg := range outbox {
    c, err := net.Dial("tcp", "127.0.0.1:9999")
    if err != nil {
        fmt.Println(err)
        return
    }

    if err != nil {
        fmt.Println("error encoding the response to a join request")
        fmt.Println(err)
    }
    b, _ := json.Marshal(msg)
    fmt.Printf("the json: %s
", b)
    c.Write(b)
    c.Close()
}
time.Sleep(time.Second * 2)
}

func New(myPid int, ConFile string) Envelope {
inbox = make(chan *Envelope, 100)
outbox = make(chan *Envelope, 100)
file, err := os.Open(ConFile)
if err != nil {
    fmt.Println("Error:", err)
}
defer file.Close()
reader := csv.NewReader(file)

i := 0
j := 0
for {
    record, err := reader.Read()
    if err == io.EOF {
        break
    } else if err != nil {
        fmt.Println("Error:", err)
    }
    x, _ := strconv.Atoi(record[0])
    pids[i] = x
    i++
    ips[j] = record[1]
    j++
}

fmt.Println("
", ips)
fmt.Println("
", pids)
MsgId := rand.Int63n(0x10000000)
server = Envelope{Pid: myPid, MsgId: MsgId, Msg: "Hello World :)"}

go server_()
go client()
var input string
fmt.Println("

Press enter ---

")
fmt.Scanln(&input)
return server
}

func main() {
//for i := 1; i <= 10; i++ {
server := New(12, "config.txt")

server.Outbox() <- &Envelope{Pid: BROADCAST, MsgId: server.MsgId, Msg: "hello there"}
select {
case envelope := <-server.Inbox():
    fmt.Printf("Received msg from %d: '%s'
", envelope.Pid, envelope.Msg)

case <-time.After(2 * time.Second):
    println("Waited and waited. Ab thak gaya
")
}

//fmt.Println(server.Pid, server.MsgId, server.Msg )
//}

}

From client function I am trying to send some data but unable to receive data in handleServerConnection()

my program is written in go language help me out

I have referred most of the examples given in the book and stack overflow

i am getting an empty object in handleconnection function

展开全部

  • 写回答

1条回答 默认 最新

  • douao3636 2014-02-25 14:18
    关注

    Can you share an example of the json you are trying to decode? I suspect that it is an annotations issue. Most json is lowercase due to the javascript syntax.

    For instance, I suspect your json looks like this:

    {"pid":"0", "msgId":"500", "msg":"this is the message"}
    

    If that is the case, then you need annotations on your struct like this:

    type Envelope struct {
        Pid   int         `json:"pid"`
        MsgId int64       `json:"msgId"`
        Msg   interface{} `json:"msg"`
    }
    

    Again, without an example, I'm only guessing that this is your problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 为什么投影机用酷喵播放电影放一段时间就播放不下去了?提示发生未知故障,有什么解决办法吗?
  • ¥15 来个会搭建付费网站的有偿
  • ¥100 有能够实现人机模式的c/c++代码,有图片背景等,能够直接进行游戏
  • ¥20 校园网认证openwrt插件
  • ¥15 以AT89C51单片机芯片为核心来制作一个简易计算器,外部由4*4矩阵键盘和一个LCD1602字符型液晶显示屏构成,内部由一块AT89C51单片机构成,通过软件编程可实现简单加减乘除。
  • ¥15 求GCMS辅导数据分析
  • ¥30 SD中的一段Unet下采样代码其中的resnet是谁跟谁进行残差连接
  • ¥15 Unet采样阶段的res_samples问题
  • ¥15 Open GL ES 的使用
  • ¥15 我如果只想表示节点的结构信息,使用GCN方法不进行训练可以吗
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部