go语言网络编程
Posted ycz0926
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言网络编程相关的知识,希望对你有一定的参考价值。
服务端
package main import ( "fmt" "log" "net" ) func main() { fmt.Println("server has been started ...") tcpAddr, err := net.ResolveTCPAddr("tcp", ":8080") if err != nil { log.Println(err) } tcpListener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { log.Println(err) } ConnMap := make(map[string]*net.TCPConn) for { tcpConn, err := tcpListener.AcceptTCP() if err != nil { log.Println(err) } defer func() { _ = tcpConn.Close() }() ConnMap[tcpConn.RemoteAddr().String()] = tcpConn fmt.Println("client info: ", tcpConn.RemoteAddr().String()) } }
客户端
package main import ( "bufio" "fmt" "log" "net" "os" ) func main() { tcpAddr, err := net.ResolveTCPAddr("tcp", ":8080") conn, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { log.Println(err) } defer func() { _ = conn.Close() }() ch := make(chan int) for { inputReader := bufio.NewReader(os.Stdin) input, err := inputReader.ReadString(‘ ‘) if err != nil { log.Println(err) } b := []byte(input) n, err := conn.Write(b) if err != nil { log.Println(err) continue } fmt.Printf("write %d bytes ", n) select { case <- ch: fmt.Println("error") return default: // } } }
以上是关于go语言网络编程的主要内容,如果未能解决你的问题,请参考以下文章