duan02143 2018-01-22 10:56
浏览 212
已采纳

如何在Go中从netcat打印TCP消息?

So I need to write a server in Go that prints messages from the following command:

echo "MESSAGE" | nc localhost 8080

It just has to print "MESSAGE" as a string on stdout. I can not use something else, it has to be this command. This is what I have so far:

package main

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

func main() {
  ln, err := net.Listen("tcp", ":8080")
  check(err)
  for {
    conn, err := ln.Accept()
    check(err)
    go handleConnection(conn)
  }
}

func handleConnection(conn net.Conn) {
  buf := make([]byte, 1024)
  reqLen, err := conn.Read(buf)
  fmt.Println(reqLen)
  check(err)
  // PRINT MESSAGE HERE
  conn.Write([]byte("Message received."))
  fmt.Println(conn.RemoteAddr().String())
  conn.Close()
}


func check(err error) {
  if err != nil {
    fmt.Println("Error:" + err.Error())
    os.Exit(1)
  }
}

I need a fmt.Println(???) where the comment // PRINT MESSAGE HERE is. How can I do this? Thanks.

  • 写回答

1条回答 默认 最新

  • dongyimeng3764 2018-01-22 10:59
    关注

    To print the message in quotes, you can use the %q format specifier (see the fmt docs).

    You'll want to convert your buffer to a string and make sure you only use the part of the buffer that contains data (up to reqLen):

    // buf[:reqLen] is a slice of the first reqLen bytes of buf.
    // string(...) creates a string from a slice of bytes.
    fmt.Printf("Message contents: %q
    ", string(buf[:reqLen]))
    

    This will print:

    Message contents: "message
    "
    

    The is inserted by echo. If you don't want it, run echo -n ..., or strip surrounding whitespace/newlines using strings.TrimSpace.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么