conn, err := net.Dial("tcp", "localhost:9000") if err != nil { log.Fatal(err) } defer conn.Close() // Use conn to send or receive data...
listener, err := net.Listen("tcp", "localhost:8080") if err != nil { log.Fatal(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { log.Fatal(err) } // Use conn to send or receive data... }The above example creates a TCP server on the localhost at port number 8080. It listens for incoming connections and accepts them one by one in a loop. We handle errors and ensure that the listener is properly closed before the function returns. In both examples, we use the net package library to establish a TCP connection or server. With the TCPConn, we can send or receive data over the network.