This article 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 ending the program exitChan := make(chan int) // Run the server concurrently go server("127.0.0.1:7001", exitChan) // Channel blocking, waiting for the return value to be received code := <-exitChan // Mark the program's return value and exit (code) } // Service logic, incoming address and exit channelfunc server(address string, exitChan chan int) { // Listen according to the given address l, err := ("tcp", address) // If an error occurs when listening, print the error and exit if err != nil { (()) exitChan <- 1 } // Print the listening address, indicating that the listening is successful ("listen: " + address) // Delay shutdown of the listener defer () // Listen to loop for { // Accept is blocking when the new connection does not arrive conn, err := () // Any listening error occurs, print the error and exit the server if err != nil { (()) continue } // Open the session according to the connection, this process needs to be executed in parallel go handleSession(conn, exitChan) } } // Connected session logicfunc handleSession(conn , exitChan chan int) { ("Session started:") // Create a network connection data reader reader := (conn) // Receive data loop for { // Read the string until it hits Enter and return str, err := ('\n') // The data is read correctly if err == nil { // Remove the carriage return at the end of the string str = (str) // Process Telnet commands if !processTelnetCommand(str, exitChan) { () break } // Echo logic, what data should be sent, return as it is ([]byte(str + "\r\n")) } else { // An error occurred ("Session closed") () break } } } //Command processingfunc processTelnetCommand(str string, exitChan chan int) bool { // @close command indicates the end of this session if (str, "@close") { ("Session closed") // Tell the outside to disconnect return false // @shutdown directive indicates the service process being terminated } else if (str, "@shutdown") { ("Server shutdown") // Write 0 into the channel, blocking and waiting for the receiver to process exitChan <- 0 // Tell the outside to disconnect return false } // Print the input string (str) return true }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.