if err != nil {
if err == io.EOF {
logger.Info("connection close")
h.activeConn.Delete(client)
} else {
logger.Warn(err)
}
return
}
// 正在处理业务,不要关掉
client.Waiting.Add(1)
// 将数据原封不动写回去,测试
b := []byte(msg)
_, _ = conn.Write(b)
client.Waiting.Done()
}
}
func (h *EchoHandler) Close() error {
logger.Info("handler shutting down...")
h.closing.Set(true)
h.activeConn.Range(func(key interface{}, val interface{}) bool {
client := key.(*EchoClient)
_ = client.Close()
return true
})
return nil
}
- MakeEchoHandler:创建EchoHandler
- Handle:处理客户端的连接。
- 1.连接正在关闭时,不接收新连接
- 2.存储新连接,value用空结构体
- 3.使用缓存区接收用户发来的数据,使用\n作为结束的标志
- Close:将所有客户端连接关掉
main.go
const configFile string = "redis.conf"
var defaultProperties = &config.ServerProperties{
Bind: "0.0.0.0",
Port: 6379,
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
return err == nil && !info.IsDir()
}
func main() {
logger.Setup(&logger.Settings{
Path: "logs",
Name: "godis",
Ext: "log",
TimeFormat: "2022-02-02",
})
if fileExists(configFile) {
config.SetupConfig(configFile)
} else {
config.Properties = defaultProperties
}
err := tcp.ListenAndServeWithSignal(
&tcp.Config{
Address: fmt.Sprintf("%s:%d",
config.Properties.Bind,
config.Properties.Port),
},
EchoHandler.MakeHandler())
if err != nil {
logger.Error(err)
}
}