【问题标题】:How to send an Integer to a TCP server in Golang?如何将整数发送到 Golang 中的 TCP 服务器?
【发布时间】:2021-08-28 00:21:51
【问题描述】:

我在 Go 中有以下客户端和服务器:

客户:

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
    "io"
    "net"
)

func main() {

var num1 int
buf := new(bytes.Buffer)

fmt.Scanln(&num1)

fmt.Printf("I'm the client, your input was the number: %d", num1)

//escribir el numero a b, el buffer
err := binary.Write(buf, binary.LittleEndian, num1)

//Llama al server
conn, err := net.Dial("tcp", "localhost:9000")
if err != nil {
    panic(err)
}

//Escribe buffer a la conexion
buf.WriteTo(conn)

//Cierra la conexión
defer conn.Close()

//Lee la conexión  y la imprime
bs, _ := io.ReadAll(conn)
fmt.Println(string(bs))
}

服务器:

package main

import (
    "encoding/binary"
    "fmt"
    "io"
    "net"
)

func main() {
//Escuchar un request
ln, err := net.Listen("tcp", ":9000")
if err != nil {
    panic(err)
}

defer ln.Close()
var num int

for {

    //Recibir un request
    conn, err := ln.Accept()
    if err != nil {
        panic(err)
    }

    err = binary.Read(conn, binary.LittleEndian, &num)

    io.WriteString(conn, fmt.Sprintf("I'm the server, the number I received is: ", num))

    conn.Close()
}
}

我的服务器正在发回消息,但显然它收到的是 0 而不是用户输入的数字。看起来这应该是一件简单的事情,但我想不通。

我不确定我是否正在尝试正确的实现来做到这一点。有没有更好的办法?如果没有,为什么我的服务器没有正确接收 int?

【问题讨论】:

    标签: go tcp


    【解决方案1】:

    始终处理错误。

    调用binary.Read(conn, binary.LittleEndian, &num)binary.Write(buf, binary.LittleEndian, num1) 返回一个错误,指出不支持ints。

    encoding/binary 包适用于固定大小的数字 (doc)。 int 的大小不是固定大小,因为大小取决于平台。

    在客户端声明num1 和在服务器中声明num 以使用固定大小的类型。例如,将两个声明都更改为int32

    向 Sprintf 调用添加格式动词。我在这里添加 %v:

    io.WriteString(conn, fmt.Sprintf("I'm the server, the number I received is: %v", num))
    

    Example modified to run on the Playground.

    【讨论】:

    • 谢谢!这是向 TCP 服务器发送数据的常用方法还是有更好的方法?
    • @samuel-amg 二进制编码是通过 TCP 发送数据的常用方式。
    猜你喜欢
    • 2021-09-05
    • 2018-12-17
    • 2023-03-23
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多