gpt4 book ai didi

go - 使用客户端连接到服务器的行为与telnet不同

转载 作者:行者123 更新时间:2023-12-01 22:37:59 28 4
gpt4 key购买 nike

我想为this Go server写一个简单的客户端。当我使用telnet从CMD连接到服务器时,它可以正常工作,即当客户端连接时,服务器会要求输入用户名,但是当我尝试从以下客户端进行连接时:

package main

import (
"bufio"
"fmt"
"net"
"os"
)

func main() {

// connect to this socket
conn, _ := net.Dial("tcp", "127.0.0.1:8181")
for {
// read in input from stdin
reader := bufio.NewReader(os.Stdin)
fmt.Print("Write to send: ")
text, _ := reader.ReadString('\n')

// send to socket
fmt.Fprintf(conn, text)
// listen for reply
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message from server: " + message)
}
}


服务器始终停留在一条消息中。例如,在我运行服务器并尝试从客户端连接后:

服务器输出:
D:\>go run server.go
2019/11/10 22:07:19 listening on: 127.0.0.1:8181
2019/11/10 22:07:24 createclient: remote connection from: 127.0.0.1:55565
2019/11/10 22:07:29 new client created: 127.0.0.1:55565 devy

客户输出:
D:\>go run client.go
Write to send: devy
Message from server: Please Enter Name: ---------------------------
Write to send:

但是我希望客户端登录时首先显示来自服务器的消息“请输入名称:---------------------------”

最佳答案

您正在从stdin中读取内容,然后将其发送到服务器。如果服务器发送“请输入名称”字符串,则必须首先从服务器读取,然后从stdin读取,然后将读取的内容写入服务器。

for {
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message from server: " + message)
// read in input from stdin
reader := bufio.NewReader(os.Stdin)
fmt.Print("Write to send: ")
text, _ := reader.ReadString('\n')
// send to socket
fmt.Fprintf(conn, text)
}

关于go - 使用客户端连接到服务器的行为与telnet不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792524/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com