// inspired from: // https://github.com/mactsouk/opensource.com.git // and // https://coderwall.com/p/wohavg/creating-a-simple-tcp-server-in-go package main import "bufio" // import "fmt" import "math/rand" import "net" // import "os" import "strconv" import "strings" import "time" import "log" const MIN = 1 const MAX = 100 const ( CONN_HOST = "localhost" CONN_PORT = "3333" CONN_TYPE = "tcp" ) func main() { // // Listen for incoming connections. l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT) if err != nil { log.Println("Error listening:", err.Error()) return } // Close the listener when the application closes. defer l.Close() log.Println("Listening on " + CONN_HOST + ":" + CONN_PORT) rand.Seed(time.Now().Unix()) for { // Listen for an incoming connection. conn, err := l.Accept() if err != nil { log.Println("Error accepting: ", err.Error()) return } // Handle connections in a new goroutine. go handleConnection(conn) } } func random() int { return rand.Intn(MAX-MIN) + MIN } func handleConnection(c net.Conn) { log.Printf("Serving %s\n", c.RemoteAddr().String()) for { netData, err := bufio.NewReader(c).ReadString('\n') if err != nil { log.Println(err) return } temp := strings.TrimSpace(string(netData)) if temp == "STOP" { break } log.Println("Recieved: ", temp) result := strconv.Itoa(random()) + "\n" c.Write([]byte(string(result))) } c.Close() }