1 Star 0 Fork 0

Clannad/webkit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 2.39 KB
一键复制 编辑 原始数据 按行查看 历史
yokaqa 提交于 2024-10-18 10:22 . 111
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package main
import (
"context"
"fmt"
"io"
"time"
"gitee.com/clannad_sk/webkit/v2/frame/g"
"gitee.com/clannad_sk/webkit/v2/net/gtcp"
"gitee.com/clannad_sk/webkit/v2/os/gctx"
"gitee.com/clannad_sk/webkit/v2/os/gtime"
"gitee.com/clannad_sk/webkit/v2/os/gtimer"
)
const (
AddressOfServer1 = ":8198"
AddressOfServer2 = ":8199"
UpStream = "127.0.0.1:8198"
)
var (
ctx = gctx.GetInitCtx()
)
// StartTCPServer1 starts Server1: A simple tcp server for demo.
// It reads the content from client connect and write it back to client.
func StartTCPServer1() {
s := g.TCPServer(1)
s.SetHandler(func(conn *gtcp.Conn) {
defer conn.Close()
for {
data, err := conn.Recv(-1)
if err != nil {
g.Log().Errorf(ctx, `%+v`, err)
break
}
if len(data) > 0 {
err = conn.Send([]byte(fmt.Sprintf(`received: %s`, data)))
if err != nil {
g.Log().Errorf(ctx, `%+v`, err)
break
}
}
}
})
s.SetAddress(AddressOfServer1)
s.Run()
}
// StartTCPServer2 starts Server2:
// All requests to Server2 are directly redirected to Server1.
func StartTCPServer2() {
s := g.TCPServer(2)
s.SetHandler(func(conn *gtcp.Conn) {
defer conn.Close()
// Each client connection associates an upstream connection.
upstreamClient, err := gtcp.NewConn(UpStream)
if err != nil {
_, _ = conn.Write([]byte(fmt.Sprintf(
`cannot connect to upstream "%s": %s`, UpStream, err.Error(),
)))
return
}
// Redirect the client connection reading and writing to upstream connection.
for {
go io.Copy(upstreamClient, conn)
_, err = io.Copy(conn, upstreamClient)
if err != nil {
_, _ = conn.Write([]byte(fmt.Sprintf(
`io.Copy to upstream "%s" failed: %s`, UpStream, err.Error(),
)))
}
}
})
s.SetAddress(AddressOfServer2)
s.Run()
}
func main() {
go StartTCPServer1()
go StartTCPServer2()
time.Sleep(time.Second)
gtimer.Add(ctx, time.Second, func(ctx context.Context) {
address := fmt.Sprintf(`127.0.0.1%s`, AddressOfServer2)
result, err := gtcp.SendRecv(address, []byte(gtime.Now().String()), -1)
if err != nil {
g.Log().Errorf(ctx, `send data failed: %+v`, err)
}
g.Log().Info(ctx, result)
})
g.Listen()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/clannad_sk/webkit.git
git@gitee.com:clannad_sk/webkit.git
clannad_sk
webkit
webkit
997199055094

搜索帮助