go语言实现简单回射服务器

服务器:

import (
	"fmt"
	"net"
	"time"
)

func ReverData(conn net.Conn) {
	//var buff [128]byte
	//buff := make([]byte, 128)
	defer conn.Close()

	for {
		buff := make([]byte, 128)
		n, err := conn.Read(buff)

		if err != nil {
			fmt.Println("client closed")
			return
		}
		fmt.Println("recv ", n, " bytes msg:", string(buff[0:n]))
		//conn.Write([]byte("ok"))
		conn.Write(buff)
		//fmt.Println("send : ", buff)
	}
}
func main() {
	mysocket, err := net.Listen("tcp", "localhost:8080")
	if err != nil {
		fmt.Println("mysocket bind error")
		return
	}

	defer mysocket.Close()
	go Weat()
	for {
		conn, err := mysocket.Accept()
		if err != nil {
			continue
		}
		fmt.Println("connet")
		go ReverData(conn)
	}
}
func Weat() {
	for {
		time.Sleep(20 * time.Second)
		fmt.Println("weating...")
	}
}

客户端:

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

func SendData(conn net.Conn) {
	//buff := make([]string, 128)
	var buff string
	for {
		fmt.Println("input:")
		//使用scanf输入,不能识别空格
		//fmt.Scanf("%s\n", &buff)

		//使用bufio输入,正常
		input := bufio.NewReader(os.Stdin)
		buff, _ = input.ReadString('\n')
		buff = buff[0 : len(buff)-2]

		//如果是end直接结束程序,strings.compare()和C语言一样,返回值是数值
		if strings.Compare(buff, "end") == 0 {
			fmt.Println("The use end...")
			return
		}

		conn.Write([]byte(buff))
		buff = buff[:0]

		buf := make([]byte, 128)
		conn.Read(buf)
		fmt.Println("recv from server:", string(buf[0:len(buf)]))

		buff = ""
	}

	fmt.Println("client closed")
}
func main() {
	mysocket, err := net.Dial("tcp", "localhost:8080")
	if err != nil {
		fmt.Println("net.dial error")
		return
	}

	defer mysocket.Close()
	SendData(mysocket)
	//mysocket.Write([]byte("hello world"))
	//fmt.Println("send success")
}

猜你喜欢

转载自blog.csdn.net/zhanglu_1024/article/details/79540049
今日推荐