Skip to content

Instantly share code, notes, and snippets.

@elazarl
Created June 11, 2013 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elazarl/5754861 to your computer and use it in GitHub Desktop.
Save elazarl/5754861 to your computer and use it in GitHub Desktop.
This code snippet demonstrate the tcp simultaneous connection feature. No one of the goroutines has a listening socket, yet, when both try to connect to each other simultaneously the connection succeeds. I've yet to understand what is this feature good for, I definitely know what is it not good for: http://golang.org/src/pkg/net/tcpsock_posix.go…
package main
import "fmt"
import "net"
var localhost = net.ParseIP("127.0.0.1")
var port1, port2 = 1220, 1229
func conwrite() {
c1, err := net.DialTCP("tcp", &net.TCPAddr{localhost, port2}, &net.TCPAddr{localhost, port1})
if err != nil {
panic(err)
}
c1.Write([]byte("hoho"))
}
func conread() {
buf := make([]byte, 100)
c1, err := net.DialTCP("tcp", &net.TCPAddr{localhost, port1}, &net.TCPAddr{localhost, port2})
if err != nil {
panic(err)
}
nr, err := c1.Read(buf)
if err != nil {
panic(err)
}
fmt.Println("Got", string(buf[:nr]))
}
func main() {
go conwrite()
conread()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment