Skip to content

Instantly share code, notes, and snippets.

@kaid
Last active November 25, 2016 05:17
Show Gist options
  • Save kaid/4286b5222c2c1f9572a8d53cf0a575c1 to your computer and use it in GitHub Desktop.
Save kaid/4286b5222c2c1f9572a8d53cf0a575c1 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"io"
"net"
"strings"
"sync"
)
func handleReq(conn net.Conn) error {
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
return err
}
fmt.Print("Message Received:", string(message))
conn.Write([]byte(strings.ToUpper(message) + "\n"))
}
}
func main() {
fmt.Println("Launching server...")
ln, _ := net.Listen("tcp", ":8081")
defer ln.Close()
count := 0
conns := make(chan net.Conn)
errs := make(chan error)
go func() {
for {
conn, _ := ln.Accept()
conns <- conn
}
}()
mutex := &sync.Mutex{}
for {
select {
case conn := <-conns:
mutex.Lock()
count += 1
mutex.Unlock()
println("active clients: ", count)
go func(conn net.Conn) {
err := handleReq(conn)
if err != nil {
conn.Close()
errs <- err
}
}(conn)
case err := <-errs:
if err == io.EOF {
mutex.Lock()
count -= 1
mutex.Unlock()
println("active clients: ", count)
} else {
println(err.Error())
}
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment