You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
141 lines
2.2 KiB
141 lines
2.2 KiB
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"io"
|
|
"io/ioutil"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
Message = "Pong"
|
|
StopCharacter = "\r\n\r\n"
|
|
)
|
|
|
|
func SocketServer(port int) {
|
|
|
|
listen, err := net.Listen("tcp4", ":"+strconv.Itoa(port))
|
|
defer listen.Close()
|
|
if err != nil {
|
|
log.Fatalf("Socket listen port %d failed,%s", port, err)
|
|
os.Exit(1)
|
|
}
|
|
log.Printf("Begin listen for command on port: %d", port)
|
|
|
|
for {
|
|
conn, err := listen.Accept()
|
|
if err != nil {
|
|
log.Fatalln(err)
|
|
continue
|
|
}
|
|
go handler(conn)
|
|
}
|
|
|
|
}
|
|
|
|
func handler(conn net.Conn) {
|
|
|
|
defer conn.Close()
|
|
|
|
var (
|
|
buf = make([]byte, 1024)
|
|
r = bufio.NewReader(conn)
|
|
w = bufio.NewWriter(conn)
|
|
)
|
|
|
|
ILOOP:
|
|
for {
|
|
n, err := r.Read(buf)
|
|
data := string(buf[:n])
|
|
|
|
switch err {
|
|
case io.EOF:
|
|
break ILOOP
|
|
case nil:
|
|
log.Println("Receive:", data)
|
|
if isTransportOver(data) {
|
|
log.Println("Tranport Over!")
|
|
break ILOOP
|
|
}
|
|
|
|
go handleCommand(data)
|
|
|
|
default:
|
|
log.Fatalf("Receive data failed:%s", err)
|
|
return
|
|
}
|
|
|
|
}
|
|
w.Write([]byte(Message))
|
|
w.Flush()
|
|
log.Printf("Send: %s", Message)
|
|
|
|
}
|
|
|
|
func handleCommand(command string) {
|
|
args := strings.Split(command, " ")
|
|
|
|
if len(args) <= 0 {
|
|
return
|
|
}
|
|
|
|
switch command := args[0]; command {
|
|
case "init":
|
|
{
|
|
handleInitCommand(args[1:])
|
|
}
|
|
case "close":
|
|
{
|
|
log.Println("close command")
|
|
}
|
|
}
|
|
}
|
|
|
|
func handleInitCommand(args []string) {
|
|
log.Println("Init command", args)
|
|
// create local config file
|
|
localConfig := "node_config.txt"
|
|
out, err := os.Create(localConfig)
|
|
if err != nil {
|
|
log.Fatal("Failed to create local file")
|
|
}
|
|
defer out.Close()
|
|
|
|
// get remote config file
|
|
configURL := args[0]
|
|
resp, err := http.Get(configURL)
|
|
if err != nil {
|
|
log.Fatal("Failed to read file content")
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// copy remote to local
|
|
_, err = io.Copy(out, resp.Body)
|
|
if err != nil {
|
|
log.Fatal("Failed to copy file")
|
|
}
|
|
|
|
content, err := ioutil.ReadFile(localConfig)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
log.Printf("File contents: %s", content)
|
|
}
|
|
|
|
func isTransportOver(data string) (over bool) {
|
|
over = strings.HasSuffix(data, "\r\n\r\n")
|
|
return
|
|
}
|
|
|
|
func main() {
|
|
|
|
port := 3333
|
|
|
|
SocketServer(port)
|
|
|
|
}
|
|
|