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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题