Golang tcp客户端服务器程序

时间:2016-10-02 17:28:55

标签: go

我可以做服务器程序或客户端程序,但我不知道如何做客户端/服务器程序。 有人知道这段代码有什么问题吗?感谢。

package main

import (
    "net"
    "os"
    "bufio"
    "io"
)

func main() {
    listen, _ := net.Listen("tcp", "localhost:9001")


dial, _ := net.Dial("tcp", "localhost:9002")


scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    conn, _ := listen.Accept()
    if scanner.Text() == "a"{
        conn.Close()
        listen.Close()
        dial.Close()
        break
    }
    dial.Write([]byte(scanner.Text()))

    io.Copy(os.Stdout, conn)
}

}

1 个答案:

答案 0 :(得分:0)

package main

import (
    "net"
    "sync"
    "log"
    "bufio"
    "os"
    "io"
    "time"
)

func receiveConn() net.Conn {
    for{
        xx, err := net.Dial("tcp", "localhost:9002")
        if err == nil{
            return xx
        }
        time.Sleep(1 * time.Second)
    }
}

var wg sync.WaitGroup

func main() {
    wg.Add(2)

    go func() {
        listen, err := net.Listen("tcp", "localhost:9001")
        if err != nil {
            log.Fatal(err)
        }
        defer listen.Close()

        for {
            conn, err := listen.Accept()
            defer conn.Close()
            if err != nil {
                log.Fatal(err)
            }

            io.Copy(os.Stdout, conn)

        }
    }()

    go func() {
        dial := receiveConn()

        defer dial.Close()
        scanner := bufio.NewScanner(os.Stdin)
        for scanner.Scan() {
            if scanner.Text() == "a"{
                dial.Write([]byte("Your mate has left the room"))
                break
            }
            dial.Write([]byte(scanner.Text() + "\n"))
        }
    }()

    wg.Wait()
}

解决!!!!

相关问题