其他分享
首页 > 其他分享> > gob

gob

作者:互联网

package main

import (
	"bufio"
	"encoding/gob"
	"net"
	"log"
	"time"
)
type User struct {
	Id int16
}


func main() {
	log.SetFlags(0)
	addr := make(chan string)

	go func(addr chan string) {
		lis, err := net.Listen("tcp", ":8080")
		if err != nil {
			log.Fatal(err)
		}
		addr <- lis.Addr().String()
	
		for {
			conn, err := lis.Accept()
			if err != nil {
				continue;
			}
			var data User
			err = gob.NewDecoder(conn).Decode(&data)
			log.Println(data)
			conn.Close()
		}
	}(addr)

	conn, err := net.Dial("tcp", <-addr)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	data := &User{123}
	buf := bufio.NewWriter(conn)
	gob.Register(User{})
	err = gob.NewEncoder(buf).Encode(data)
	buf.Flush()
	if err != nil {
		log.Fatal(err)
	}
	time.Sleep(time.Second)
}

标签:log,err,gob,data,conn,addr
来源: https://blog.csdn.net/qq_38858546/article/details/115557135