server1.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "net"
  6. "strings"
  7. )
  8. // Map of the clients: contains: clientname - 1 (active) / 0 - (inactive)
  9. var mapUsers map[string]int
  10. func main() {
  11. var listener net.Listener
  12. var error error
  13. var conn net.Conn
  14. mapUsers = make(map[string]int)
  15. fmt.Println("Starting the server ...")
  16. // create listener:
  17. listener, error = net.Listen("tcp", "localhost:50000")
  18. checkError(error)
  19. // listen and accept connections from clients:
  20. for {
  21. conn, error = listener.Accept()
  22. checkError(error)
  23. go doServerStuff(conn)
  24. }
  25. }
  26. func doServerStuff(conn net.Conn) {
  27. var buf []byte
  28. var error error
  29. for {
  30. buf = make([]byte, 512)
  31. _, error = conn.Read(buf)
  32. checkError(error)
  33. input := string(buf)
  34. if strings.Contains(input, ": SH") {
  35. fmt.Println("Server shutting down.")
  36. os.Exit(0)
  37. }
  38. // op commando WHO: write out mapUsers
  39. if strings.Contains(input, ": WHO") {
  40. DisplayList()
  41. }
  42. // extract clientname:
  43. ix := strings.Index(input, "says")
  44. clName := input[0:ix-1]
  45. //fmt.Printf("The clientname is ---%s---\n", string(clName))
  46. // set clientname active in mapUsers:
  47. mapUsers[string(clName)] = 1
  48. fmt.Printf("Received data: --%v--", string(buf))
  49. }
  50. }
  51. // advantage: code is cleaner,
  52. // disadvantage: the server process has to stop at any error:
  53. // a simple return continues in the function where we came from!
  54. func checkError(error error) {
  55. if error != nil {
  56. panic("Error: " + error.Error()) // terminate program
  57. }
  58. }
  59. func DisplayList() {
  60. fmt.Println("--------------------------------------------")
  61. fmt.Println("This is the client list: 1=active, 0=inactive")
  62. for key, value := range mapUsers {
  63. fmt.Printf("User %s is %d\n", key, value)
  64. }
  65. fmt.Println("--------------------------------------------")
  66. }