Golang tcp客户机-服务器程序
我可以做服务器程序或客户端程序,但我不知道如何做客户端/服务器程序。 有人知道这个代码出了什么问题吗?谢谢Golang tcp客户机-服务器程序,go,Go,我可以做服务器程序或客户端程序,但我不知道如何做客户端/服务器程序。 有人知道这个代码出了什么问题吗?谢谢 package main import ( "net" "os" "bufio" "io" ) func main() { listen, _ := net.Listen("tcp", "localhost:9001") dial, _ := net.Dial("tcp", "localhost:9002") scanner := buf
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)
}
}
解决了 感谢Bart缩进de代码。
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()
}