-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.go
117 lines (86 loc) · 2.32 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
/* ThreadedIPEchoServer
*/
package main
import (
"fmt"
"net"
"os"
"runtime"
)
var cmdServer = &Command{
Run: runServer,
UsageLine: "server",
Short: "start up a server",
Long: "start up a server",
}
// func main() {
func runServer(cmd *Command, args []string) bool {
fmt.Fprintf(os.Stderr, "number of cpus:%d:\n", NCPU)
fmt.Fprintf(os.Stderr, "number of cpus as reported by go:%d:\n", runtime.NumCPU())
runtime.GOMAXPROCS(NCPU)
command_listener, err := net.Listen("tcp", SERVICE)
checkError(err)
defer command_listener.Close()
go listenTCPCommands(command_listener)
// data_listener, err := net.ListenPacket("udp", service)
// checkError(err)
// defer data_listener.Close()
// for i := 0; i < NCPU; i++ {
// go handleData(data_listener, i)
// }
var input string
fmt.Scanln(&input)
return true
}
func listenTCPCommands(listener net.Listener) {
for {
conn, err := listener.Accept()
if err != nil {
fmt.Fprintf(os.Stderr, "failed to accept:retrying:%t:\n", err)
continue
}
rv, err := TtpNegotiate(conn)
if err != nil {
checkError(err)
return
}
if rv != true {
fmt.Fprintf(os.Stderr, "protocol mismatch:continuing anyway:\n")
// return
}
go handleTCPCommands(conn)
}
}
//handle commands on the tcp connection
//this need something better than silent death upon read/write error
//for now just be an echo server
func handleTCPCommands(conn net.Conn) {
var buf [BUF_SIZE]byte
for {
//go into echo server mode
n, err := conn.Read(buf[0:])
if err != nil {
return
}
_, err2 := conn.Write(buf[0:n])
if err2 != nil {
return
}
}
}
func handleData(conn net.PacketConn, cpu int) {
var buf [BUF_SIZE]byte
for {
fmt.Fprintf(os.Stderr, "about to read:cpu:%d:\n", cpu)
n, addr, err := conn.ReadFrom(buf[0:])
fmt.Fprintf(os.Stderr, "read bytes:%d:cpu:%d:buf:%s:\n", n, cpu, buf)
if err != nil {
return
}
wrote, err2 := conn.WriteTo(buf[0:n], addr)
fmt.Fprintf(os.Stderr, "wrote bytes:%d:cpu:%d:\n", wrote, cpu)
if err2 != nil {
return
}
}
}