map-ify clients, handle left message.

This commit is contained in:
Andrey Petrov 2014-12-09 18:22:46 -08:00
parent 939c4273ff
commit da934daf4a
3 changed files with 27 additions and 6 deletions

View File

@ -15,7 +15,7 @@ build: $(BINARY)
clean:
rm $(BINARY)
key: $(KEY)
$(KEY):
ssh-keygen -f $(KEY) -P ''
run: $(BINARY) $(KEY)

View File

@ -1,4 +1,15 @@
ssh-chat
========
# ssh-chat
Coming real soon.
## TODO:
* Welcome message.
* set term width properly
* client map rather than list
* backfill chat history
* tab completion
* /help
* /about
* /list

View File

@ -13,7 +13,7 @@ type Server struct {
sshConfig *ssh.ServerConfig
sshSigner *ssh.Signer
done chan struct{}
clients []Client
clients map[Client]struct{}
lock sync.Mutex
}
@ -38,6 +38,7 @@ func NewServer(privateKey []byte) (*Server, error) {
sshConfig: &config,
sshSigner: &signer,
done: make(chan struct{}),
clients: map[Client]struct{}{},
}
return &server, nil
@ -45,7 +46,7 @@ func NewServer(privateKey []byte) (*Server, error) {
func (s *Server) Broadcast(msg string, except *Client) {
logger.Debugf("Broadcast to %d: %s", len(s.clients), strings.TrimRight(msg, "\r\n"))
for _, client := range s.clients {
for client := range s.clients {
if except != nil && client == *except {
continue
}
@ -90,12 +91,21 @@ func (s *Server) Start(laddr string) error {
// TODO: mutex this
s.lock.Lock()
s.clients = append(s.clients, *client)
s.clients[*client] = struct{}{}
num := len(s.clients)
s.lock.Unlock()
s.Broadcast(fmt.Sprintf("* Joined: %s (%d present)\r\n", client.Name, num), nil)
go func() {
sshConn.Wait()
s.lock.Lock()
delete(s.clients, *client)
s.lock.Unlock()
s.Broadcast(fmt.Sprintf("* Left: %s\r\n", client.Name), nil)
}()
go client.handleChannels(channels)
}()
}