Handling multiple connections using goroutines
This commit is contained in:
parent
a4a5594096
commit
a41033f150
|
@ -4,31 +4,38 @@ import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ln, err := net.Listen("tcp", ":1302")
|
ln, err := net.Listen("tcp", ":1302")
|
||||||
catchErr(err)
|
catchErr(err)
|
||||||
fmt.Println("Listening on port 1302")
|
fmt.Printf("Listening on port 1302...\n")
|
||||||
|
|
||||||
conn, err := ln.Accept()
|
|
||||||
catchErr(err)
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
|
conn, err := ln.Accept()
|
||||||
|
catchErr(err)
|
||||||
|
go handleConn(conn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleConn(conn net.Conn) {
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
message, err := bufio.NewReader(conn).ReadString('\n')
|
message, err := bufio.NewReader(conn).ReadString('\n')
|
||||||
catchErr(err)
|
catchErr(err)
|
||||||
fmt.Printf("Message received: %v", string(message))
|
fmt.Printf("Message received: %v", string(message))
|
||||||
newMsg := strings.ToUpper(message)
|
newMsg := strings.ToUpper(message)
|
||||||
conn.Write([]byte(newMsg + "\n"))
|
conn.Write([]byte(newMsg + "\n"))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func catchErr(err error) (errHappened bool) {
|
func catchErr(err error) (errHappened bool) {
|
||||||
errHappened = false
|
errHappened = false
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errHappened = true
|
errHappened = true
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
return errHappened
|
return errHappened
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue