Created
February 23, 2017 21:02
-
-
Save aka-mj/8bf683808615fde6467b0b264721f22f to your computer and use it in GitHub Desktop.
TCP Socket Example in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// go run main.go | |
package main | |
import ( | |
"bytes" | |
"fmt" | |
"net" | |
"os" | |
"time" | |
) | |
func listen(end chan<- bool) { | |
addr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:10111") | |
if err != nil { | |
fmt.Printf("listen: Failed to resolve: %v\n", err) | |
os.Exit(1) | |
} | |
lnt, err := net.ListenTCP("tcp4", addr) | |
if err != nil { | |
fmt.Printf("listen: Failed to listen: %v\n", err) | |
os.Exit(1) | |
} | |
conn, err := lnt.AcceptTCP() | |
if err != nil { | |
fmt.Printf("listen: Failed on accept: %v\n", err) | |
os.Exit(1) | |
} | |
// Receive message | |
buf := make([]byte, 2048) | |
n, err := conn.Read(buf) | |
if err != nil { | |
fmt.Printf("listen: Failed to read: %v\n", err) | |
} else { | |
fmt.Printf("listen: Received %v bytes\n >>\t%v\n", n, string(buf)) | |
// Send a message back | |
conn.Write(buf) | |
} | |
conn.Close() | |
lnt.Close() | |
end <- true | |
} | |
func dial(end chan<- bool) { | |
raddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:10111") | |
if err != nil { | |
fmt.Printf("dial: Failed to resolve remote: %v\n", err) | |
os.Exit(1) | |
} | |
laddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:0") | |
if err != nil { | |
fmt.Printf("dial: Failed to resolve local: %v\n", err) | |
os.Exit(1) | |
} | |
conn, err := net.DialTCP("tcp4", laddr, raddr) | |
if err != nil { | |
fmt.Printf("dial: Failed to connect: %v\n", err) | |
os.Exit(1) | |
} | |
// Send a message | |
var buf bytes.Buffer | |
buf.WriteString("Hello from sender") | |
n, err := conn.Write(buf.Bytes()) | |
if err != nil { | |
fmt.Printf("dial: Failed to send: %v\n", err) | |
} else { | |
fmt.Printf("dial: Sent %v bytes\n", n) | |
rbuf := make([]byte, 2048) | |
// Receive reply | |
n, _ = conn.Read(rbuf) | |
fmt.Printf("dial: Received: %v\n", string(rbuf[:n])) | |
} | |
conn.Close() | |
end <- true | |
} | |
func main() { | |
end := make(chan bool, 2) | |
go listen(end) | |
time.Sleep(time.Second) | |
go dial(end) | |
<-end | |
<-end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment