douliaopan1419 2012-12-29 13:17
浏览 309
已采纳

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

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.

  • 写回答

2条回答 默认 最新

  • dqtiober37522 2012-12-29 13:35
    关注

    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('
    ')
            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.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python