server.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package unchat
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. )
  7. //A Server is a proposed type to hold details about itself and connected clients
  8. type Server struct {
  9. alias string
  10. version string
  11. port int32
  12. clients map[string]Client
  13. listener net.Listener
  14. }
  15. //NewServer initialize a standard server with common attributes
  16. func NewServer(alias string) Server {
  17. return Server{
  18. alias: alias,
  19. port: 9999,
  20. version: "default",
  21. }
  22. }
  23. //Open expects the port and the ip address which a TCP listener will be started
  24. func (s *Server) Open(listenAddress string) {
  25. var server net.Listener
  26. address := fmt.Sprintf("%s:%d", listenAddress, s.port)
  27. server, err := net.Listen("TCPV4", address)
  28. s.listener = server
  29. if err != nil {
  30. log.Fatalf("could not listen on %s %s", address, err)
  31. }
  32. defer s.listener.Close()
  33. for {
  34. conn, err := s.listener.Accept()
  35. if err != nil {
  36. log.Fatalf("could not accept connection %s", err)
  37. }
  38. go s.handleConnection(conn)
  39. defer conn.Close()
  40. }
  41. }
  42. func (s *Server) handleConnection(conn net.Conn) {
  43. c := &Client{
  44. client: conn,
  45. alias: "undefined",
  46. server: s,
  47. }
  48. if s.clients == nil {
  49. s.clients = make(map[string]Client)
  50. }
  51. s.clients[c.alias] = *c
  52. s.Broadcast(fmt.Sprintf("> %s has joined the server", c.alias))
  53. c.ReadInput()
  54. }
  55. //Broadcast sends a message to all connected clients
  56. func (s *Server) Broadcast(message string) error {
  57. for _, v := range s.clients {
  58. err := v.SendMessage(message)
  59. if err != nil {
  60. log.Printf("count not broadcast to %s: %s", s.alias, err)
  61. }
  62. }
  63. return nil
  64. }