英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论