Created
June 11, 2013 06:36
-
-
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…
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
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