├── README.md └── main.go /README.md: -------------------------------------------------------------------------------- 1 | Multi-threaded TCP Server 2 | === 3 | 4 | This codebase demonstartes multi-threaded tcp server in Golang. 5 | For detailed explanation please refer to the following video 6 | 7 | - https://youtu.be/f9gUFy-9uCM 8 | 9 | ## How to Run 10 | 11 | ``` 12 | $ go run main.go 13 | ``` 14 | 15 | Fire the following commands on another terminal to simulate 16 | multiple concurrent requests. 17 | 18 | ``` 19 | $ curl http://localhost:1729 & 20 | $ curl http://localhost:1729 & 21 | $ curl http://localhost:1729 & 22 | ``` 23 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net" 6 | "time" 7 | ) 8 | 9 | func do(conn net.Conn) { 10 | buf := make([]byte, 1024) 11 | _, err := conn.Read(buf) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | 16 | log.Println("processing the request") 17 | time.Sleep(8 * time.Second) 18 | 19 | conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\nHello, World!\r\n")) 20 | conn.Close() 21 | } 22 | 23 | func main() { 24 | listener, err := net.Listen("tcp", ":1729") 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | 29 | for { 30 | log.Println("waiting for a client to connect") 31 | conn, err := listener.Accept() 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | log.Println("client connected") 36 | 37 | go do(conn) 38 | } 39 | } 40 | --------------------------------------------------------------------------------