1024programmer Java go network programming 38 – concurrency

go network programming 38 – concurrency

TCP client

package mainimport ("fmt""net""os"
)func main() {//Actively connect to the server conn, err:= net.Dial("tcp", "")if err != nil {fmt.Println("Dial err = ", err)return}//Close the connection defer conn.Close ()//Input content from the keyboard and send content to the server go func() {//Slice cache buf_key:= make([]byte, 1024)for {num, err:= os.Stdin.Read (buf_key)if err != nil {fmt.Println("os.Stdin.Read err = ", err)return}//Send data conn.Write(buf_key[:num])fmt.Println ("client send buf = ", string(buf_key[:num]))}}()//Receive the data buf replied by the server:= make([]byte, 1024)for {num, err := conn.Read(buf)if err != nil { //When the read fails, the main coroutine exits directly fmt.Println("Read err = ", err )return}fmt.Println("client recv buf = ", string(buf[:num]))}

TCP server

package mainimport ("fmt""net""strings"
)func HandleConn(conn net.Conn) {//Automatically close the connection defer conn.Close()//Get the customer End network address information addr:= conn.RemoteAddr().String()fmt.Println(addr, "connect success!")buf:= make([]byte, 2*1024)for {/ /Read user data num, err:= conn.Read(buf)if err != nil {fmt.Println("Read err = ", err)return}fmt.Printf(" [%s]:read buf = %s", addr, string(buf[:num]))//TCP knowledge: The newline character in the UNIX system generated after pressing the RETURN key, sent by the server to the client Yes: Carriage return and line feed characters (CR/LF),i.e. "\r\n",Their function is to move the cursor back to the left and move to the next line//Based on the above explanation: echo There will be 2 more bytes (this method is only a temporary solution) if string(buf[:num-2]) == "exit" {fmt.Println(addr, " close!")return}/ /Convert the data to uppercase and send it to the user conn.Write([]byte(strings.ToUpper(string(buf[:num]))))}
}func main() {//1. Listen, err := net.Listen("tcp", "")if err != nil {fmt.Println("Listen err = ", err)return}// Close defer listen.Close()//Receive multiple users for {conn, err:= listen.Accept()if err != nil {fmt.Println("Accept err = ", err)return}//Process the user's request (new coroutine)go HandleConn(conn)}

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/736958

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top