drozwmi5440 2016-07-07 14:37
浏览 23
已采纳

无法对允许向服务器发送文本消息的客​​户端进行编程

So I've programmed a server that receives text messages from a connecting client, reverses and capses them and sends them back.

Now I'm trying to program a client so that when I launch it it will keep running until I shut it down (ctrl + c) and allow me to input text lines and send them to the server.

I have a problem though - if I pass a, say, cyrillic symbol to the input, it will return a <nil> <nil> (type, value) error and will remain bugged unless I flush the memory somehow.

I also can't figure how to read the whole message (whole meaning the size of the slice (1024 bytes)) instead of each word separately.

Also, how do I figure out how to delay my 'enter your message' text? Depending on the length of the message I pass on to the server, it should wait longer or shorter. I don't want it popping all over the place if the message is split into a few messages, just once after the answer is received.

Here's the relevant code:

func client() {
    // connect to the server
    c, err := net.Dial("tcp", "127.0.0.1"+":"+port)
    if err != nil {
        log.Printf("Dial error: %T %+v", err, err)
        return
    }

    // send the message
    msg := ""
    for {
    fmt.Print("Enter your message:
")
    _, errs := fmt.Scan(&msg)
    if errs != nil {
        log.Printf("Scan error: %T %+v", errs, errs)
        return
    }
    fmt.Println("Client sending:
", msg)
    _, errw := c.Write([]byte(msg))
    if errw != nil {
        log.Printf("Write error: %T %+v", errw, errw)
        return
    }
    // handle the response
    go handleServerResponse(c)
    time.Sleep(1 * time.Second)
}

func main() {
    port = "9999"

    // launch client
    done := make(chan bool)
    go client()
    <-done // Block forever
}

I've used the empty channel to block the main() from ending.

How should I approach the 2 problems explained above?

  • 写回答

1条回答 默认 最新

  • douyong2531 2016-07-09 15:41
    关注

    Question answered by @JimB:

    You're using fmt.Scan which scans space separated values. Don't use that if you don't want to read each value separately. You can use Scanln to read a line, or just read directly from stdin.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题