Created
August 28, 2013 05:04
-
-
Save tristanwietsma/6362315 to your computer and use it in GitHub Desktop.
TCP Client & Server (ping-pong)
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 ( | |
"net" | |
"log" | |
"time" | |
) | |
func Ping(proto, addr string, out chan<- string) { | |
c, err := net.Dial(proto, addr) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer c.Close() | |
msg := []byte("holla!") | |
_, err = c.Write(msg) | |
if err != nil { | |
log.Fatal(err) | |
} | |
buf := make([]byte, 1024) | |
_, err = c.Read(buf) | |
if err != nil { | |
log.Fatal(err) | |
} | |
out <- string(buf) | |
} | |
func main() { | |
start := time.Now() | |
ch := make(chan string, 1) | |
for i := 0; i < 100; i++ { | |
go Ping("tcp", "0.0.0.0:8888", ch) | |
} | |
var m string | |
for i := 0; i < 100; i++ { | |
m = <-ch | |
log.Println(i+1, m) | |
} | |
log.Println(time.Since(start)) | |
} |
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 ( | |
"net" | |
"log" | |
) | |
func HandleConn(c net.Conn) { | |
defer c.Close() | |
// handle incoming data | |
buffer := make([]byte, 1024) | |
numBytes, err := c.Read(buffer) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println("received", numBytes, "bytes:", string(buffer)) | |
// handle reply | |
msg := string(buffer[:numBytes]) + " back" | |
_, err = c.Write([]byte(msg)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func main() { | |
l, err := net.Listen("tcp", "0.0.0.0:8888") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer l.Close() | |
for { | |
// accept connection | |
log.Println("Waiting for new connection...") | |
conn, err := l.Accept() | |
if err != nil { | |
log.Fatal(err) | |
} | |
// handle connection | |
go HandleConn(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment