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: clean:
rm $(BINARY) rm $(BINARY)
key: $(KEY) $(KEY):
ssh-keygen -f $(KEY) -P '' ssh-keygen -f $(KEY) -P ''
run: $(BINARY) $(KEY) run: $(BINARY) $(KEY)

View File

@ -1,4 +1,15 @@
ssh-chat # ssh-chat
========
Coming real soon. 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 sshConfig *ssh.ServerConfig
sshSigner *ssh.Signer sshSigner *ssh.Signer
done chan struct{} done chan struct{}
clients []Client clients map[Client]struct{}
lock sync.Mutex lock sync.Mutex
} }
@ -38,6 +38,7 @@ func NewServer(privateKey []byte) (*Server, error) {
sshConfig: &config, sshConfig: &config,
sshSigner: &signer, sshSigner: &signer,
done: make(chan struct{}), done: make(chan struct{}),
clients: map[Client]struct{}{},
} }
return &server, nil return &server, nil
@ -45,7 +46,7 @@ func NewServer(privateKey []byte) (*Server, error) {
func (s *Server) Broadcast(msg string, except *Client) { func (s *Server) Broadcast(msg string, except *Client) {
logger.Debugf("Broadcast to %d: %s", len(s.clients), strings.TrimRight(msg, "\r\n")) 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 { if except != nil && client == *except {
continue continue
} }
@ -90,12 +91,21 @@ func (s *Server) Start(laddr string) error {
// TODO: mutex this // TODO: mutex this
s.lock.Lock() s.lock.Lock()
s.clients = append(s.clients, *client) s.clients[*client] = struct{}{}
num := len(s.clients) num := len(s.clients)
s.lock.Unlock() s.lock.Unlock()
s.Broadcast(fmt.Sprintf("* Joined: %s (%d present)\r\n", client.Name, num), nil) 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) go client.handleChannels(channels)
}() }()
} }