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  = "

Hello World

" i := (Int)(len(respBody)) fmt.Println("响应的消息体长度:"+i.toStr()) //返回的http消息头 var respHeader = "HTTP/1.1 200 OK\n"+ "Content-Type: text/html;charset=ISO-8859-1\n"+ "Content-Length: "+i.toStr() //拼装http返回的消息 resp := respHeader +"\n\r\n"+ respBody fmt.Println(resp) n, _ := conn.Write([]byte(resp)) fmt.Printf("发送的数据数量:%s\n",(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) } }

  golang模拟编程tcp模拟http(转载)_第1张图片

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

转载于:https://www.cnblogs.com/K-artorias/p/11589858.html

你可能感兴趣的:(golang模拟编程tcp模拟http(转载))