-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_keepalive.go
More file actions
71 lines (63 loc) · 1.58 KB
/
tcp_keepalive.go
File metadata and controls
71 lines (63 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"strings"
"time"
)
func main() {
listener, err := net.Listen("tcp", "localhost:8888")
if err != nil {
panic(err)
}
fmt.Println("Server is running at localhost:8888")
for {
conn, err := listener.Accept()
if err != nil {
panic(err)
}
go func() {
fmt.Printf("Accept %v\n", conn.RemoteAddr())
// Accept後のソケットで何度も応答を返すためにループ
for {
// タイムアウトを設定
conn.SetReadDeadline(time.Now().Add(4 * time.Second))
// リクエストを読み込む
request, err := http.ReadRequest(bufio.NewReader(conn))
// タイムアウト or ソケットクローズ時は終了。それ以外はエラー
if err != nil {
neterr, ok := err.(net.Error) // 型アサーションを使用してエラーがnet.Error型であるかどうかを確認
if ok && neterr.Timeout() {
fmt.Println("timeout")
break
} else if err == io.EOF {
break
}
panic(err)
}
// リクエストを表示
dump, err := httputil.DumpRequest(request, true)
if err != nil {
panic(err)
}
fmt.Println(string(dump))
// レスポンスの書き込み(HTTP/1.1かつContentLengthの設定が必要)
content := "Done"
response := http.Response{
StatusCode: 200,
ProtoMajor: 1,
ProtoMinor: 1,
ContentLength: int64(len(content)),
Body: ioutil.NopCloser(strings.NewReader("Done")),
}
response.Write(conn)
}
conn.Close()
}()
}
}