Implementation of Telnet echo server in go language

Time:2020-11-17

This paper introduces the go language telnet echo server and shares it with you. The details are as follows:

package main

import (
  "fmt"
  "net"
  "bufio"
  "strings"
  "os"
)

func main() {

  //Create a channel for program end code
  exitChan := make(chan int)

  //Run the server concurrently
  go server("127.0.0.1:7001", exitChan)

  //Channel blocked, waiting to receive return value
  code := <-exitChan

  //Mark the program return value and exit
  os.Exit(code)
}

//Service logic, incoming address and exit channel
func server(address string, exitChan chan int) {

  //Listen according to the given address
  l, err := net.Listen("tcp", address)

  //If there is an error in listening, print the error and exit
  if err != nil {
   fmt.Println(err.Error())
   exitChan <- 1
  }

  //Print listening address, indicating successful listening
  fmt.Println("listen: " + address)

  //Delay shutdown listener
  defer l.Close()

  //Listening loop
  for {

   //When a new connection does not arrive, accept is blocked
   conn, err := l.Accept()

   //Any listening errors occur, print errors and exit the server
   if err != nil {
     fmt.Println(err.Error())
     continue
   }

   //Opening a session based on the connection requires parallel execution
   go handleSession(conn, exitChan)
  }
}

//Session logic of connection
func handleSession(conn net.Conn, exitChan chan int) {

  fmt.Println("Session started:")

  //Create a reader for network connection data
  reader := bufio.NewReader(conn)

  //Cycle of receiving data
  for {

   //Read the string until a carriage return is encountered
   str, err := reader.ReadString('\n')

   //Data read correctly
   if err == nil {

     //Remove the carriage return at the end of the string
     str = strings.TrimSpace(str)

     //Processing telnet instructions
     if !processTelnetCommand(str, exitChan) {
      conn.Close()
      break
     }

     //Echo logic, send what data, return as is
     conn.Write([]byte(str + "\r\n"))

   } else {
     //An error occurred
     fmt.Println("Session closed")
     conn.Close()
     break
   }
  }

}

//Command processing
func processTelnetCommand(str string, exitChan chan int) bool {

  //The @ close command means to terminate the session
  if strings.HasPrefix(str, "@close") {

   fmt.Println("Session closed")

   //Tell the outside that you need to disconnect
   return false

   //The @ shutdown command terminates the service process
  } else if strings.HasPrefix(str, "@shutdown") {

   fmt.Println("Server shutdown")

   //Write 0 to the channel, block and wait for the receiver to process
   exitChan <- 0

   //Tell the outside that you need to disconnect
   return false
  }

  //Print the input string
  fmt.Println(str)

  return true

}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.