Go language network communication --- TCP programming for multi-user continuous communication

Server side:

package main 

import ( 
	"fmt" 
	"net" 
) 

func main () { 
	// Create monitoring 
	listener, err: = net.Listen ("tcp", "localhost: 8080") 
	if err! = nil { 
		fmt.Println (" Failed to establish tcp monitoring, err = ", err) 
		return 
	} 

	defer func () { 
		listener.Close () 
		fmt.Println (" Server is closed ") 
	} () 

	fmt.Println (" Listening to client requests ") 

	for { 
		/ / Cycle access to a client (acquiring a dedicated line connection Conn) 
		conn, _: = listener.Accept () 
		fmt.Println ("Successful access to the client:", conn.RemoteAddr ()) 

		// Throw the connected client into the concurrent coroutine for processing 
		go func () { 
			/ * In a separate concurrent task with the current client IO * / 
			for { 
				// In the dedicated line connection with Specific client IO 
				buffer: = make ([] byte, 1024)
				n, _: = conn.Read (buffer)
				msg: = string (buffer [: n]) 
				fmt.Printf ("Client% v:% s \ n", conn.RemoteAddr (), msg) 

				// Reply to the message 
				conn.Write ([] byte ("read Message: "+ msg)) 

				// Determine whether the client wants to divorce 
				if msg ==" exit "{ 
					// Disconnect from the client 
					conn.Close () 
					break 
				} 

			} 
		} () 
	} 

}

  client side:

package main 

import ( 
	"fmt" 
	"net" 
) 

func main () { 
	// Dial using udp protocol, remote address 127.0.0.1:8080 
	conn, _: = net.Dial ("tcp", "127.0.0.1:8080" ) 

	// Close the connection before the program exits and release the io resource 
	defer func () { 
		conn.Close () 
		fmt.Println ("Client has exited") 
	} () 

	// Create a buffer for receiving messages 
	: = make ([ ] byte, 1024) 
	// Message text to be sent by the user 
	var userInput string 
	for { 
		// Receive user input 
		fmt.Print ("Please input:") 
		fmt.Scan (& userInput) 
		// Exit if the user enters exit 

		// Client initiates conversation 
		conn.Write ([] byte (userInput)) 

		// Receive server message 
		n, err: = conn.Read (buffer) 
		fmt.Println (err) 
		fmt.Println ("Server:"+string(buffer[:n]))
		if userInput == "exit"{
			break
		}
	}
}

  

Guess you like

Origin www.cnblogs.com/yunweiqiang/p/12727600.html