Skip to content

Instantly share code, notes, and snippets.

@tristanwietsma
Created August 28, 2013 05:04
Show Gist options
  • Save tristanwietsma/6362315 to your computer and use it in GitHub Desktop.
Save tristanwietsma/6362315 to your computer and use it in GitHub Desktop.
TCP Client & Server (ping-pong)
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))
}
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