golang模拟编程tcp模拟http(转载)

package main

import (
	"fmt"
	"net"
	"strconv"
)

//用来转化int为string
type Int int

func (i Int)toStr()string  {
	return strconv.FormatInt(int64(i),10)
}

func testConn(conn net.Conn){
	addr := conn.RemoteAddr()
	fmt.Println(addr)
	//返回的http消息体
	var respBody  = "<h1>Hello World<h1>"
	i := (Int)(len(respBody))
	fmt.Println("响应的消息体长度:"+i.toStr())
	//返回的http消息头
	var respHeader  = "HTTP/1.1 200 OK
"+
		"Content-Type: text/html;charset=ISO-8859-1
"+
		"Content-Length: "+i.toStr()
	//拼装http返回的消息
	resp := respHeader +"

"+ respBody
	fmt.Println(resp)
	n, _ := conn.Write([]byte(resp))
	fmt.Printf("发送的数据数量:%s
",(Int)(n).toStr())
}

func main() {
	listen, err := net.Listen("tcp", "127.0.0.1:8888")
	if err !=nil{
		fmt.Println(err)
		return
	}
	defer listen.Close() //延时关闭 listen

	for{
		conn, err := listen.Accept()
		if err !=nil{
			fmt.Println(err)
			continue
		}
		go testConn(conn)
	}
}

  

 转载地址:https://blog.csdn.net/weixin_37910453/article/details/86679694

原文地址:https://www.cnblogs.com/K-artorias/p/11589858.html