在Go中的服务器,重定向到标准输出

huangapple go评论89阅读模式
英文:

Server in Go, redirection to stdout

问题

如何在Go中实现一个服务器,将每个传入的行发送到标准输出?

package main

import (
    "io"
    "log"
    "net"
    "bufio"
)

func main() {
    srv, err := net.Listen("tcp", ":2000")
    if err != nil {
        log.Fatal(err)
    }
    for {
        conn, err := srv.Accept()
        if err != nil {
            log.Fatal(err)
        }
        go func(c net.Conn) {
            defer c.Close()
            reader := bufio.NewReader(c)
            for {
                line, err := reader.ReadString('\n')
                if err != nil {
                    if err == io.EOF {
                        break
                    }
                    log.Println(err)
                    break
                }
                log.Println(line)
            }
        }(conn)
    }
}
英文:

How I can implement a server in Go, which sends each incomming line to stdout ?

package main

import (
	"io"
	"log"
	"net"
)

func main() {
	srv, err := net.Listen("tcp", ":2000")
	for {
		conn, err := srv.Accept()
		go func(c net.Conn) {
            
            //How to split here by lines ?

			c.Close()
		}(conn)
	}
}

After runing the server with

./server

And running telnet

telnet localhost 2000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
test 123
foobar

I want to see on stdout where I started the server:

test 123
foobar

I know this code lacks error handling, but this is only for clearity to show what I'm trying to do.

答案1

得分: 7

由于net.Conn是一个io.Reader,您可以将其包装在一个bufio.Reader中,并在该类型上使用ReadString方法。您的函数将变为

func(c net.Conn) {
    f := bufio.NewReader(c)
    for {
        ln, err := f.ReadString('\n')
        if err == io.EOF {
            break
        } else if err != nil {
            panic(err)
        }
        fmt.Print(ln)
    }
    c.Close()
}

(我不确定Go中的stdout是否同步;在一个单独的goroutine中循环遍历共享通道上的行可能更清晰。)

英文:

Since a net.Conn is an io.Reader, you can wrap it in a bufio.Reader and use the ReadString method on that type. Your function would become

func(c net.Conn) {
    f := bufio.NewReader(c)
    for {
        ln, err := f.ReadString('\n')
        if err == io.EOF {
            break
        } else if err != nil {
            panic(err)
        }
        fmt.Print(ln)
    }
    c.Close()
}

(I'm not sure if stdout is synchronized in Go; it might be cleaner to send the lines on a shared channel that is looped over in a separate goroutine.)

答案2

得分: 5

如果这是你想要的全部,只需将套接字复制到标准输出。

package main

import (
	"io"
	"log"
	"net"
	"os"
)

func main() {
	srv, err := net.Listen("tcp", ":2000")
	if err != nil {
		log.Fatalf("Error listening: %v", err)
	}
	for {
		conn, err := srv.Accept()
		if err != nil {
			log.Fatalf("Error accepting: %v", err)
		}
		go func(c net.Conn) {
			defer c.Close()
			io.Copy(os.Stdout, c)
		}(conn)
	}
}
英文:

If that's all you want, just copy the socket to stdout.

package main

import (
	"io"
	"log"
	"net"
	"os"
)

func main() {
	srv, err := net.Listen("tcp", ":2000")
	if err != nil {
		log.Fatalf("Error listening: %v", err)
	}
	for {
		conn, err := srv.Accept()
		if err != nil {
			log.Fatalf("Error accepting: %v", err)
		}
		go func(c net.Conn) {
			defer c.Close()
			io.Copy(os.Stdout, c)
		}(conn)
	}
}

huangapple
  • 本文由 发表于 2012年12月29日 21:17:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/14082063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定