How to send an Integer to a TCP server in Golang?

huangapple go评论81阅读模式
英文:

How to send an Integer to a TCP server in Golang?

问题

我用Go编写了以下客户端和服务器:

客户端:

package main

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

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

	fmt.Scanln(&num1)

	fmt.Printf("我是客户端,你输入的数字是:%d", num1)

	// 将数字写入缓冲区
	err := binary.Write(buf, binary.LittleEndian, num1)

	// 连接服务器
	conn, err := net.Dial("tcp", "localhost:9000")
	if err != nil {
		panic(err)
	}

	// 将缓冲区写入连接
	buf.WriteTo(conn)

	// 关闭连接
	defer conn.Close()

	// 读取连接并打印
	bs, _ := io.ReadAll(conn)
	fmt.Println(string(bs))
}

服务器:

package main

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

func main() {
	// 监听请求
	ln, err := net.Listen("tcp", ":9000")
	if err != nil {
		panic(err)
	}

	defer ln.Close()
	var num int

	for {
		// 接受请求
		conn, err := ln.Accept()
		if err != nil {
			panic(err)
		}

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

		io.WriteString(conn, fmt.Sprintf("我是服务器,我接收到的数字是:%d", num))

		conn.Close()
	}
}

我的服务器返回了消息,但似乎接收到的是0而不是用户输入的数字。这似乎应该是一个简单的操作,但我无法解决。

我不确定我是否尝试了正确的实现方式。有没有更好的方法?如果没有,为什么我的服务器没有正确接收到整数?

英文:

I have the following client and server in Go:

Client:

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))
}

Server:

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()
}
}

My server is sending back the message, but apparently its receiving a 0 instead of the number input by the user. It seems like this should be a simple thing to do but I can't figure it out.

Im not sure if I'm trying the correct implementation to do this. Is there a better way? And if not, why is my server not receiving the int properly?

答案1

得分: 2

始终处理错误。

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

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

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

在Sprintf调用中添加一个格式化占位符。我在这里添加了%v:

io.WriteString(conn, fmt.Sprintf("我是服务器,我收到的数字是:%v", num))

修改后的示例可在Playground上运行

英文:

Always handle errors.

The call binary.Read(conn, binary.LittleEndian, &num) and binary.Write(buf, binary.LittleEndian, num1) return an error stating that ints are not supported.

The encoding/binary package works with fixed sized numbers (doc). The size of an int is not fixed size because the size is platform dependent.

Declarenum1 in the client and num in the server to use fixed sized types. For example, change both declarations to int32.

Add a format verb to the Sprintf call. I add %v here:

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

Example modified to run on the Playground.

huangapple
  • 本文由 发表于 2021年6月11日 10:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/67930530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定