dongpaipu8394 2011-09-22 15:00
浏览 8
已采纳

您如何在Go中有效使用网络功能?

For example, having basic packet protocol, like:

[packetType int][packetId int][data []byte]

And making a client and server doing simple things with it (egx, chatting.)

  • 写回答

2条回答 默认 最新

  • doulei6330 2011-09-22 21:46
    关注

    Here's a client and server with sloppy panic error-handling. They have some limitations:

    • The server only handles one client connection at a time. You could fix this by using goroutines.
    • Packets always contain 100-byte payloads. You could fix this by putting a length in the packet somewhere and not using encoding/binary for the entire struct, but I've kept it simple.

    Here's the server:

    package main
    
    import (
        "encoding/binary"
        "fmt"
        "net"
    )
    
    type packet struct {
        // Field names must be capitalized for encoding/binary.
        // It's also important to use explicitly sized types.
        // int32 rather than int, etc.
        Type int32
        Id   int32
        // This must be an array rather than a slice.
        Data [100]byte
    }
    
    func main() {
        // set up a listener on port 2000
        l, err := net.Listen("tcp", ":2000")
        if err != nil {
            panic(err.String())
        }
    
        for {
            // start listening for a connection
            conn, err := l.Accept()
            if err != nil {
                panic(err.String())
            }
            handleClient(conn)
        }
    }
    
    func handleClient(conn net.Conn) {
        defer conn.Close()
    
        // a client has connected; now wait for a packet
        var msg packet
        binary.Read(conn, binary.BigEndian, &msg)
        fmt.Printf("Received a packet: %s
    ", msg.Data)
    
        // send the response
        response := packet{Type: 1, Id: 1}
        copy(response.Data[:], "Hello, client")
        binary.Write(conn, binary.BigEndian, &response)
    }
    

    Here's the client. It sends one packet with packet type 0, id 0, and the contents "Hello, server". Then it waits for a response, prints it, and exits.

    package main
    
    import (
        "encoding/binary"
        "fmt"
        "net"
    )
    
    type packet struct {
        Type int32
        Id   int32
        Data [100]byte
    }
    
    func main() {
        // connect to localhost on port 2000
        conn, err := net.Dial("tcp", ":2000")
        if err != nil {
            panic(err.String())
        }
        defer conn.Close()
    
        // send a packet
        msg := packet{}
        copy(msg.Data[:], "Hello, server")
        err = binary.Write(conn, binary.BigEndian, &msg)
        if err != nil {
            panic(err.String())
        }
    
        // receive the response
        var response packet
        err = binary.Read(conn, binary.BigEndian, &response)
        if err != nil {
            panic(err.String())
        }
        fmt.Printf("Response: %s
    ", response.Data)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c