-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstreznik.go
65 lines (57 loc) · 1.32 KB
/
streznik.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
// Komunikacija po protokolu TCP
// niz pred pošiljanjem pretvorimo v []byte, ob prejemu pa []byte v niz
// strežnik
package main
import (
"fmt"
"net"
"os"
"strings"
"time"
)
func Server(url string) {
// izpišemo ime strežnika
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
fmt.Printf("TCP (string) server listening at %v%v\n", hostname, url)
// odpremo vtičnico
listener, err := net.Listen("tcp", url)
if err != nil {
panic(err)
}
for {
// čakamo na odjemalca
connection, err := listener.Accept()
if err != nil {
fmt.Println(err)
continue
}
// obdelamo zahtevo
go handleRequest(connection)
}
}
func handleRequest(conn net.Conn) {
// na koncu zapremo povezavo
defer conn.Close()
// sprejememo sporočilo
bMsgRecv := make([]byte, 1024)
n, err := conn.Read(bMsgRecv)
if err != nil {
panic(err)
}
msgRecv := string(bMsgRecv[0:n])
fmt.Println("Received message:", msgRecv)
// obdelamo sporočilo
time.Sleep(5 * time.Second)
msgRecvSplit := strings.Split(msgRecv, "@")
timeNow := time.Now().Format(time.DateTime)
msgSend := fmt.Sprintf("Hello %v@ %v", msgRecvSplit[0], timeNow)
// pošljemo odgovor
fmt.Println("Sent message:", msgSend)
_, err = conn.Write([]byte(msgSend))
if err != nil {
panic(err)
}
}