Look at the code after Dubug for comments

Requirements:

The service side

  • The server establishes a TCP listener on port 8888 of the local host
  • Create a separate coroutine for each client you access
  • Receive client messages in a loop and automatically reply “read XXX” no matter what the client says.
  • If the client says “bye”, reply “bye” and disconnect

The client

  • Dial-up to port 8888 of the server host to establish the connection
  • The loop reads a line of user input from standard input (command line) and sends it to the server
  • Receives and prints the server information. If the message is bye, exit the program

Before debugging: server.go Indicates the server

packageTCP communicationsimport (
	"fmt"
	"net"
	"os"
)

func main(a) {
	listener, err := net.Listen("tcp"."127.0.0.1:8888")
	ServerHandleError(err,"net.Listen")
	for {
		conn, err := listener.Accept()
		ServerHandleError(err,"listener.Accept")
		go ChatWith(conn)
	}

}

func ChatWith(conn net.Conn) {
	buffer := make([]byte.1024)
	for {
		n, err := conn.Read(buffer)
		ServerHandleError(err,"conn.Read(buffer)")

		clientMsg := string(buffer[0:n])
		fmt.Printf("Received message from %v: %s\n",conn.RemoteAddr(),clientMsg)
		ifclientMsg! ="bye"{
			conn.Write([]byte("Read:"+clientMsg))
		}else {
			conn.Write([]byte("bye!"))
			break
		}
		conn.Close()
		fmt.Printf("Client %s is disconnected",conn.RemoteAddr())

	}

}

func ServerHandleError(err error,when string) {
	iferr ! =nil {
		fmt.Println(err,when)
		os.Exit(1)}}Copy the code

Before debug: Client. go Indicates the client

packageTCP communicationsimport (
	"bufio"
	"fmt"
	"net"
	"os"
)

func main(a) {
	conn, e:= net.Dial("tcp"."127.0.0.1:8888")
	ClientHandleError(e," net.Dial")

	buffer := make([]byte.1024)

	reader := bufio.NewReader(os.Stdin)
	for{
		lineBytes, _, _ := reader.ReadLine()
		conn.Write(lineBytes)
		n, e := conn.Read(buffer)
		ClientHandleError(e,"conn.Read(buffer)")
		serverMsg := string(buffer[0:n])
		fmt.Println("Server :"+serverMsg)
		if serverMsg=="bye!"{
			break
		}
		fmt.Println("Game over!")}}func ClientHandleError(err error,when string) {
	iferr ! =nil {
		fmt.Println(err,when)
		os.Exit(1)}}Copy the code

Compile run program

We can see that as soon as we input, we output “game over” and then disconnect.

Then I debug. According to the audit code, I find that the output game over statement and conn.close () are placed in the for loop. After modifying this, I can send and receive messages successfully.

Debug: server.go Indicates the server

package main
/ * requirements: The server establishes a TCP listening on port 8888 of the local host to open a separate coroutine loop for each client to receive the message from the client, no matter what the client says, it automatically replies with "read XXX". If the client says "bye", reply with "bye" and disconnect. The connection loop reads a line of user input from standard input (command line), sends the server to receive and print the server information, and if the message is "bye", exits the program */

import (
	"fmt"
	"net"
	"os"
)

func main(a) {
	// The server establishes a TCP listener on port 8888 of the local host
	listener, err := net.Listen("tcp"."127.0.0.1:8888")
	ServerHandleError(err,"net.Listen")

	for {
		// Loop access all clients to get private line connection
		conn, e := listener.Accept()
		ServerHandleError(e,"listener.Accept")
		// Open up a separate coroutine for the client chat
		go ChatWith(conn)
	}

}
// Talk to the client in CONN
func ChatWith(conn net.Conn) {
	// Create a message buffer
	buffer := make([]byte.1024)
	for {
		// A complete message round
		
		// Read the message sent by the client and store it in the buffer. The message length is N bytes
		n, err := conn.Read(buffer)
		ServerHandleError(err,"conn.Read(buffer)")
		// Convert to string output
		clientMsg := string(buffer[0:n])
		fmt.Printf("Received message from %v: %s\n",conn.RemoteAddr(),clientMsg)
		// Reply to the client message
		ifclientMsg! ="im off"{
			
			conn.Write([]byte("Read:"+clientMsg))
		}else {
			conn.Write([]byte("bye!"))
			// Jump out of the session
			break}}// Disconnect the client
	conn.Close()
	fmt.Printf("Client %s is disconnected",conn.RemoteAddr())

}

func ServerHandleError(err error,when string) {
	iferr ! =nil {
		fmt.Println(err,when)
		os.Exit(1)}}Copy the code

Debug: Client. Go Server

package main

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

func main(a) {
	// Dial up the remote address to establish a TCP connection
	conn, err:= net.Dial("tcp"."127.0.0.1:8888")
	ClientHandleError(err," net.Dial")
	// Prepare the message buffer
	buffer := make([]byte.1024)
	// Prepare the standard input reader
	reader := bufio.NewReader(os.Stdin)

	// A steady stream of messages
	for{
		// Receive command line input (a line of messages)
		lineBytes, _, _ := reader.ReadLine()
		// Send to the server
		conn.Write(lineBytes)
		// Receive the server message and store it in the buffer. The length is N bytes
		n, _ := conn.Read(buffef)
		// Convert to a string and print it
		serverMsg := string(buffer[0:n])
		fmt.Println("Server :",serverMsg)
		// Exit the loop if the server says bye
		if serverMsg == "bye"{
			break
		}
	}
	fmt.Println("Game over!")}func ClientHandleError(err error,when string) {
	iferr ! =nil {
		fmt.Println(err,when)
		os.Exit(1)}}Copy the code