gpt4 book ai didi

Golang tcp客户端服务器程序

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:29 24 4
gpt4 key购买 nike

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

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)
}

最佳答案

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()
}

已解决!!!!

关于Golang tcp客户端服务器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39819668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com