新聞中心
?gtcp?模塊支持?TLS?加密通信服務(wù)端及客戶(hù)端,在對(duì)安全要求比較高的場(chǎng)景中非常必要。?TLS?服務(wù)端創(chuàng)建可以通過(guò)?NewServerTLS?或者?NewServerKeyCrt?方法實(shí)現(xiàn)。?TLS?客戶(hù)端創(chuàng)建可以通過(guò)?NewConnKeyCrt?或者?NewConnTLS?方法實(shí)現(xiàn)。

使用示例:
https://github.com/GOgf/gf/v2/tree/master/.example/net/gtcp/tls
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gtcp"
"github.com/gogf/gf/v2/util/gconv"
"time"
)
func main() {
address := "127.0.0.1:8999"
crtFile := "server.crt"
keyFile := "server.key"
// TLS Server
go gtcp.NewServerKeyCrt(address, crtFile, keyFile, func(conn *gtcp.Conn) {
defer conn.Close()
for {
data, err := conn.Recv(-1)
if len(data) > 0 {
fmt.Println(string(data))
}
if err != nil {
// if client closes, err will be: EOF
g.Log().Error(err)
break
}
}
}).Run()
time.Sleep(time.Second)
// Client
conn, err := gtcp.NewConnKeyCrt(address, crtFile, keyFile)
if err != nil {
panic(err)
}
defer conn.Close()
for i := 0; i < 10; i++ {
if err := conn.Send([]byte(gconv.String(i))); err != nil {
g.Log().Error(err)
}
time.Sleep(time.Second)
if i == 5 {
conn.Close()
break
}
}
// exit after 5 seconds
time.Sleep(5 * time.Second)
}執(zhí)行后,可以看到客戶(hù)端執(zhí)行時(shí)報(bào)錯(cuò):
panic: x509: certificate has expired or is not yet valid那是因?yàn)槲覀兊淖C書(shū)是手動(dòng)創(chuàng)建的,并且已經(jīng)過(guò)期了,為了演示方便,我們?cè)诳蛻?hù)端代碼中去掉客戶(hù)端對(duì)證書(shū)的校驗(yàn)。
package main
import (
"fmt"
"github.com/gogf/gf/v2/net/gtcp"
"github.com/gogf/gf/v2/util/gconv"
"time"
)
func main() {
address := "127.0.0.1:8999"
crtFile := "server.crt"
keyFile := "server.key"
// TLS Server
go gtcp.NewServerKeyCrt(address, crtFile, keyFile, func(conn *gtcp.Conn) {
defer conn.Close()
for {
data, err := conn.Recv(-1)
if len(data) > 0 {
fmt.Println(string(data))
}
if err != nil {
// if client closes, err will be: EOF
g.Log().Error(err)
break
}
}
}).Run()
time.Sleep(time.Second)
// Client
tlsConfig, err := gtcp.LoadKeyCrt(crtFile, keyFile)
if err != nil {
panic(err)
}
tlsConfig.InsecureSkipVerify = true
conn, err := gtcp.NewConnTLS(address, tlsConfig)
if err != nil {
panic(err)
}
defer conn.Close()
for i := 0; i < 10; i++ {
if err := conn.Send([]byte(gconv.String(i))); err != nil {
g.Log().Error(err)
}
time.Sleep(time.Second)
if i == 5 {
conn.Close()
break
}
}
// exit after 5 seconds
time.Sleep(5 * time.Second)
}執(zhí)行后,終端輸出結(jié)果為:
0
1
2
3
4
5
2019-06-05 00:13:12.488 [ERRO] EOF
Stack:
1. /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/v2/geg/net/gtcp/tls/gtcp_server_client.go:25其中客戶(hù)端在5秒后關(guān)閉了連接,因此服務(wù)端在接收數(shù)據(jù)時(shí)獲取到了一個(gè)?EOF?錯(cuò)誤,這種錯(cuò)誤在正式使用中我們直接忽略,報(bào)錯(cuò)時(shí)服務(wù)端直接關(guān)閉客戶(hù)端連接即可。
本文題目:創(chuàng)新互聯(lián)GoFrame教程:GoFrameTCP組件-TLS加密
文章分享:http://www.dlmjj.cn/article/cdoheci.html


咨詢(xún)
建站咨詢(xún)
