go 做tcp服务器接收连接

tcp服务端

package main

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

func errFunc(err error, info string) {
	if err != nil {
		fmt.Println("这是错误>>",info, err)
		//return		//返回当前函数调用
		//runtime.Goexit()		//结束当前go程
		os.Exit(1) //将当前进程结束。
	}
}
func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:8001")
	errFunc(err, "net.Listen err:")
	defer listener.Close()
	conn, err := listener.Accept()
	errFunc(err, "Accpet err:")
	defer conn.Close()
	buf := make([]byte, 4096)
	n, err := conn.Read(buf)
	if n == 0 {
		return
	}
	errFunc(err, "conn.Read error")
	fmt.Printf("收到的值<<%s>> \n", string(buf[:n]))

}

输出;

浏览器输入:localhost:8001  收到的值<<GET /?a=1&b=2 HTTP/1.1
Host: 127.0.0.1:8001
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: csrftoken=bvOVUAPraivBktaiDZk2Ifxvv3hIC3DIlhp0p2EfckVRSglbAy2gJIQ0Q7GN1kq0

>>

tcp 客户端

package main

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

func main() {
	conn, err := net.Dial("tcp", "localhost:8001")
	if err != nil {
		fmt.Println("连接失败", err.Error())
		return
	}

	defer conn.Close()

	inputReader := bufio.NewReader(os.Stdin)
	for {
		input, _ := inputReader.ReadString('\n')
		trimInput := strings.Trim(input, "\r\n")
		if trimInput == "Q" {
			return
		}
		_, err := conn.Write([]byte(trimInput))
		if err != nil {
			return
		}
	}
}

tcp服务端 升级:

package main

import (
	"fmt"
	"net"
	"strings"
)

func main() {
	fmt.Println("start server...")
	listen, err := net.Listen("tcp", "0.0.0.0:8001")
	if err != nil {
		fmt.Println("监听失败")
		return
	}
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("accpet failed", err)
			continue
		}
		go process(conn)
	}
}

func process(conn net.Conn) {
	defer conn.Close()
	for {
		buf := make([]byte, 512)
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("连接断开")
			return
		}
		fmt.Printf("%s", strings.TrimSpace(string(buf[0:n])))
	}
}
posted @ 2022-03-27 16:05  ty1539  阅读(156)  评论(0编辑  收藏  举报