Skip to content

Instantly share code, notes, and snippets.

@geebee
Created February 1, 2018 19:32
Show Gist options
  • Select an option

  • Save geebee/e3afb5dbac971bdccd6fb7349d5c0833 to your computer and use it in GitHub Desktop.

Select an option

Save geebee/e3afb5dbac971bdccd6fb7349d5c0833 to your computer and use it in GitHub Desktop.
Simple TCP socket client & server
package main
import (
"bufio"
"flag"
"log"
"net"
"strconv"
"sync"
)
var wg sync.WaitGroup
func main() {
host := flag.String("host", "localhost", "host to connect to")
port := flag.String("port", "8443", "port to connect to")
count := flag.Int("count", 100, "number of messages to send")
maxClients := flag.Int("clients", 1, "number of concurrent clients")
flag.Parse()
for i := 0; i < *maxClients; i++ {
wg.Add(1)
go dialWriteDisconnect(*host+":"+*port, *count)
}
wg.Wait()
log.Println("finished")
}
func dialWriteDisconnect(host string, count int) {
defer wg.Done()
conn, _ := net.Dial("tcp", host)
for i := 0; i < count; i++ {
conn.Write([]byte(strconv.Itoa(i) + "\n"))
bytes, _ := bufio.NewReader(conn).ReadString('\n')
log.Printf("%s", bytes)
}
conn.Close()
}
package main
import (
"bufio"
"flag"
"fmt"
"io"
"net"
)
func handleConnection(conn net.Conn) {
fmt.Printf("client connected %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
defer func() {
fmt.Printf("closing client connection %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
conn.Close()
}()
bufReader := bufio.NewReader(conn)
for {
bytes, err := bufReader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
fmt.Printf("client disconnected: %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
} else {
fmt.Println(err)
}
return
}
fmt.Printf("received (%s -> %s): %s\n", conn.RemoteAddr(), conn.LocalAddr(), bytes)
conn.Write([]byte("ack: " + string(bytes)))
}
}
func main() {
port := flag.String("port", "8443", "listen port")
flag.Parse()
fmt.Println("starting server on 0.0.0.0:" + *port)
listener, err := net.Listen("tcp", ":"+*port)
if err != nil {
fmt.Println(err)
return
}
defer func() {
listener.Close()
fmt.Println("listener closed")
}()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
break
}
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment