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

时间:2019-09-26
本文章向大家介绍golang模拟编程tcp模拟http(转载),主要包括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\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)
	}
}

  

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

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