package unchat import ( "fmt" "log" "net" ) //A Server is a proposed type to hold details about itself and connected clients type Server struct { alias string version string port int32 clients map[string]Client listener net.Listener } //NewServer initialize a standard server with common attributes func NewServer(alias string) Server { return Server{ alias: alias, port: 9999, version: "default", } } //Open expects the port and the ip address which a TCP listener will be started func (s *Server) Open(listenAddress string) { var server net.Listener address := fmt.Sprintf("%s:%d", listenAddress, s.port) server, err := net.Listen("TCPV4", address) s.listener = server if err != nil { log.Fatalf("could not listen on %s %s", address, err) } defer s.listener.Close() for { conn, err := s.listener.Accept() if err != nil { log.Fatalf("could not accept connection %s", err) } go s.handleConnection(conn) defer conn.Close() } } func (s *Server) handleConnection(conn net.Conn) { c := &Client{ client: conn, alias: "undefined", server: s, } if s.clients == nil { s.clients = make(map[string]Client) } s.clients[c.alias] = *c s.Broadcast(fmt.Sprintf("> %s has joined the server", c.alias)) c.ReadInput() } //Broadcast sends a message to all connected clients func (s *Server) Broadcast(message string) error { for _, v := range s.clients { err := v.SendMessage(message) if err != nil { log.Printf("count not broadcast to %s: %s", s.alias, err) } } return nil }