duan02143
duan02143
2018-01-22 10:56

如何在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 dongyimeng3764 3年前

    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.

    点赞 评论 复制链接分享

为你推荐