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

我想为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:

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

joel126 回答:使用客户端连接到服务器的行为与telnet不同

您正在从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)
    }
本文链接:https://www.f2er.com/3127730.html

大家都在问