12
en/08.1.md
12
en/08.1.md
@@ -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))
|
||||
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
|
||||
|
||||
@@ -309,7 +307,7 @@ Setting the timeout of connections. These are suitable for use on both clients a
|
||||
|
||||
func (c *TCPConn) SetReadDeadline(t time.Time) error
|
||||
func (c *TCPConn) SetWriteDeadline(t time.Time) error
|
||||
|
||||
|
||||
Setting the write/read timeout of one connection:
|
||||
|
||||
func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error
|
||||
|
||||
Reference in New Issue
Block a user