forked from SimonWaldherr/golang-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelnet.go
executable file
·61 lines (57 loc) · 1.04 KB
/
telnet.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
package main
import (
"flag"
"fmt"
"net"
"os"
"strings"
"time"
)
func handleConnection(c net.Conn, msgchan chan<- string) {
defer c.Close()
fmt.Printf("Connection from %v established.\n", c.RemoteAddr())
c.SetReadDeadline(time.Now().Add(time.Second * 5))
buf := make([]byte, 4096)
for {
n, err := c.Read(buf)
if (err != nil) || (n == 0) {
c.Close()
break
}
msgchan <- string(buf[0:n])
}
time.Sleep(150 * time.Millisecond)
fmt.Printf("Connection from %v closed.\n", c.RemoteAddr())
c.Close()
return
}
func printMessages(msgchan <-chan string) {
var count int = 0
for {
msg := strings.TrimSpace(<-msgchan)
count++
fmt.Printf("Data %d: %s\n", count, msg)
}
}
func main() {
flag.Parse()
port := ":" + flag.Arg(0)
if port == ":" {
port = ":2223"
}
ln, err := net.Listen("tcp", port)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
msgchan := make(chan string)
go printMessages(msgchan)
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleConnection(conn, msgchan)
}
}