redesign how the connection API works

--HG--
branch : adc
This commit is contained in:
mappu 2017-11-22 20:02:30 +13:00
parent f5e516fe01
commit ffc81f52fb
2 changed files with 10 additions and 24 deletions

View File

@ -21,9 +21,8 @@ type HubConnection struct {
proto Protocol proto Protocol
// Streamed events // Event callback
processEvent func(HubEvent) processEvent func(HubEvent)
OnEvent chan HubEvent
// Private state // Private state
conn net.Conn // this is an interface conn net.Conn // this is an interface

View File

@ -6,12 +6,6 @@ type HubConnectionOptions struct {
SkipAutoReconnect bool // as above SkipAutoReconnect bool // as above
Self UserInfo Self UserInfo
NickPassword string NickPassword string
// Returning messages in async mode
NumEventsToBuffer uint
// Returning messages in sync mode
OnEventSync func(*HubConnection, HubEvent)
} }
func (this *HubConnectionOptions) prepareConnection() *HubConnection { func (this *HubConnectionOptions) prepareConnection() *HubConnection {
@ -37,32 +31,25 @@ func (this *HubConnectionOptions) prepareConnection() *HubConnection {
return &hc return &hc
} }
// Connects to an NMDC server, and spawns a background goroutine to handle // ConnectAsync connects to a hub server, and spawns a background goroutine to handle
// protocol messages. Events will be sent by channel to the returned hc.OnEvent, // protocol messages. Events will be sent by channel to the supplied onEvent channel,
// the client is responsible for selecting off this. // the client is responsible for selecting off this.
func (this *HubConnectionOptions) Connect() *HubConnection { func ConnectAsync(opts *HubConnectionOptions, onEvent chan HubEvent) *HubConnection {
hc := opts.prepareConnection()
if this.NumEventsToBuffer < 1 {
this.NumEventsToBuffer = 1
}
hc := this.prepareConnection()
hc.OnEvent = make(chan HubEvent, this.NumEventsToBuffer)
hc.processEvent = func(ev HubEvent) { hc.processEvent = func(ev HubEvent) {
hc.OnEvent <- ev onEvent <- ev
} }
go hc.worker() go hc.worker()
return hc return hc
} }
// Connects to an NMDC server, and blocks forever to handle protocol messages. // ConnectSync connects to a hub server, and blocks forever to handle protocol messages.
// Client code should supply an event handling function as hco.OnEventSync. // Client code should supply an event handling function as hco.OnEventSync.
func (this *HubConnectionOptions) ConnectSync() { func ConnectSync(opts *HubConnectionOptions, onEvent func(hub *HubConnection, ev HubEvent)) {
hc := this.prepareConnection() hc := opts.prepareConnection()
hc.OnEvent = nil
hc.processEvent = func(ev HubEvent) { hc.processEvent = func(ev HubEvent) {
this.OnEventSync(hc, ev) onEvent(hc, ev)
} }
hc.worker() hc.worker()
} }