-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
141 lines (129 loc) · 2.53 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"net"
"os"
"strconv"
"strings"
)
// COUNT: to handle the number of clients connected to the concurrent TCP server
var count = 0
// PRINTER: to help make the long else if statements cleaner, no need to write tons of times
func printer(s *bufio.Scanner, num int, c net.Conn) {
x := 1
for x <= num*2 {
s.Scan()
x++
}
s1 := s.Text() + "\n"
c.Write([]byte(string(s1)))
}
func handleConnection(c net.Conn) {
fmt.Println("Connected to a client")
fmt.Println("Hit Ctrl+C to close server\n")
for {
f, err := os.Open("quotes.txt")
if err != nil {
log.Fatal(err)
}
s := bufio.NewScanner(f)
err = s.Err()
if err != nil {
log.Fatal(err)
}
recievedText, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
fmt.Println(err)
return
}
temp := strings.TrimSpace(string(recievedText))
fmt.Println("received command from a client:", temp)
if temp == "EXIT" {
count--
break
}
if temp == "users" {
counter := strconv.Itoa(count) + "\n"
c.Write([]byte(string(counter)))
} else if temp == "r" {
r := rand.Intn(14) + 1
printer(s, r, c)
} else if temp == "1" {
num := 1
printer(s, num, c)
} else if temp == "2" {
num := 2
printer(s, num, c)
} else if temp == "3" {
num := 3
printer(s, num, c)
} else if temp == "4" {
num := 4
printer(s, num, c)
} else if temp == "5" {
num := 5
printer(s, num, c)
} else if temp == "6" {
num := 6
printer(s, num, c)
} else if temp == "7" {
num := 7
printer(s, num, c)
} else if temp == "8" {
num := 8
printer(s, num, c)
} else if temp == "9" {
num := 9
printer(s, num, c)
} else if temp == "10" {
num := 10
printer(s, num, c)
} else if temp == "11" {
num := 11
printer(s, num, c)
} else if temp == "12" {
num := 12
printer(s, num, c)
} else if temp == "13" {
num := 13
printer(s, num, c)
} else if temp == "14" {
num := 14
printer(s, num, c)
} else if temp == "15" {
num := 15
printer(s, num, c)
} else {
e := "That is not a valid command, please enter a command" + "\n"
c.Write([]byte(string(e)))
}
f.Close()
}
c.Close()
}
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide a port number!")
return
}
PORT := ":" + arguments[1]
l, err := net.Listen("tcp4", PORT)
if err != nil {
fmt.Println(err)
return
}
defer l.Close()
for {
c, err := l.Accept()
if err != nil {
fmt.Println(err)
return
}
count++
go handleConnection(c)
}
}