Fix example code bug in en/08.1

This commit is contained in:
Haibin Liu
2015-10-24 06:30:15 +08:00
committed by James Miranda
parent 00f6b75680
commit 41a738db7c

View File

@@ -266,7 +266,7 @@ Some of you may be thinking the following: this server does not do anything mean
func handleClient(conn net.Conn) {
conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // set 2 minutes timeout
request := make([]byte, 128) // set maximum request length to 128KB to prevent flood based attacks
request := make([]byte, 128) // set maximum request length to 128B to prevent flood based attacks
defer conn.Close() // close connection before exit
for {
read_len, err := conn.Read(request)
@@ -278,15 +278,13 @@ Some of you may be thinking the following: this server does not do anything mean
if read_len == 0 {
break // connection already closed by client
} else if string(request) == "timestamp" {
} else if string(request[:read_len]) == "timestamp" {
daytime := strconv.FormatInt(time.Now().Unix(), 10)
conn.Write([]byte(daytime))
} else {
daytime := time.Now().String()
conn.Write([]byte(daytime))
}
request = make([]byte, 128) // clear last read content
}
}
@@ -297,7 +295,7 @@ Some of you may be thinking the following: this server does not do anything mean
}
}
In this example, we use `conn.Read()` to constantly read client requests. We cannot close the connection because clients may issue more than one request. Due to the timeout we set using `conn.SetReadDeadline()`, the connection closes automatically when a client has not sent a request within our allotted time period. When then expiry time has elapsed, our program breaks from the `for` loop. Notice that `request` needs to be created with a max size limitation in order to prevent flood attacks. Finally, we clean the `request` array after processing every request, since `conn.Read()` appends new content to the array instead of rewriting it.
In this example, we use `conn.Read()` to constantly read client requests. We cannot close the connection because clients may issue more than one request. Due to the timeout we set using `conn.SetReadDeadline()`, the connection closes automatically after our allotted time period. When the expiry time has elapsed, our program breaks from the `for` loop. Notice that `request` needs to be created with a max size limitation in order to prevent flood attacks.
### Controlling TCP connections