@@ -2,6 +2,7 @@ package server
22
33import (
44 "strconv"
5+ "sync"
56
67 "github.com/wendy512/go-iecp5/asdu"
78 "github.com/wendy512/go-iecp5/clog"
@@ -23,8 +24,11 @@ type LogCfg struct {
2324}
2425
2526type Server struct {
26- settings * Settings
27- cs104Server * cs104.Server
27+ settings * Settings
28+ cs104Server * cs104.Server
29+ connections sync.Map // map[string]asdu.Connect
30+ connectionHandler func (asdu.Connect )
31+ connectionLostHandler func (asdu.Connect )
2832}
2933
3034func NewSettings () * Settings {
@@ -48,10 +52,13 @@ func New(settings *Settings, handler CommandHandler) *Server {
4852 cs104Server .SetLogProvider (logCfg .LogProvider )
4953 }
5054
51- return & Server {
55+ s := & Server {
5256 settings : settings ,
5357 cs104Server : cs104Server ,
5458 }
59+ cs104Server .SetOnConnectionHandler (s .internalConnectionHandler )
60+ cs104Server .SetConnectionLostHandler (s .internalConnectionLostHandler )
61+ return s
5562}
5663
5764func (s * Server ) Start () {
@@ -65,10 +72,38 @@ func (s *Server) Stop() {
6572
6673// SetOnConnectionHandler set on connect handler
6774func (s * Server ) SetOnConnectionHandler (f func (asdu.Connect )) {
68- s .cs104Server . SetOnConnectionHandler ( f )
75+ s .connectionHandler = f
6976}
7077
7178// SetConnectionLostHandler set connect lost handler
7279func (s * Server ) SetConnectionLostHandler (f func (asdu.Connect )) {
73- s .cs104Server .SetConnectionLostHandler (f )
80+ s .connectionLostHandler = f
81+ }
82+
83+ // GetConnections get current connections
84+ func (s * Server ) GetConnections () []asdu.Connect {
85+ connects := make ([]asdu.Connect , 0 )
86+ s .connections .Range (func (key , value any ) bool {
87+ connects = append (connects , value .(asdu.Connect ))
88+ return true
89+ })
90+ return connects
91+ }
92+
93+ func (s * Server ) internalConnectionHandler (conn asdu.Connect ) {
94+ addr := conn .UnderlyingConn ().RemoteAddr ().String ()
95+ s .connections .Store (addr , conn )
96+
97+ if s .connectionHandler != nil {
98+ s .connectionHandler (conn )
99+ }
100+ }
101+
102+ func (s * Server ) internalConnectionLostHandler (conn asdu.Connect ) {
103+ addr := conn .UnderlyingConn ().RemoteAddr ().String ()
104+ s .connections .Delete (addr )
105+
106+ if s .connectionLostHandler != nil {
107+ s .connectionLostHandler (conn )
108+ }
74109}
0 commit comments