zoukankan      html  css  js  c++  java
  • 7.2 tcpclient 基本web

    
    package main
    
    import (
    	"bufio"
    	"context"
    	"fmt"
    	"io"
    	"net"
    	"net/http"
    	"time"
    )
    
    type StringServer string
    
    func (s StringServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    	rw.Write([]byte(string(s)))
    }
    
    func createServer(addr string) http.Server {
    	return http.Server{
    		Addr:    addr,
    		Handler: StringServer("HELLO GOPHER!
    "),
    	}
    }
    
    const addr = "localhost:7070"
    
    func main() {
    	s := createServer(addr)
    	go s.ListenAndServe()
    
    	// Connect with plain TCP
    	conn, err := net.Dial("tcp", addr)
    	if err != nil {
    		panic(err)
    	}
    	defer conn.Close()
    
    	_, err = io.WriteString(conn, "GET / HTTP/1.1
    Host: localhost:7070
    
    ")
    	if err != nil {
    		panic(err)
    	}
    
    	scanner := bufio.NewScanner(conn)
    	conn.SetReadDeadline(time.Now().Add(time.Second))
    	for scanner.Scan() {
    		fmt.Println(scanner.Text())
    	}
    
    	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    	s.Shutdown(ctx)
    
    }
    
    /*
    HTTP/1.1 200 OK
    Date: Fri, 23 Mar 2018 15:46:56 GMT
    Content-Length: 14
    Content-Type: text/plain; charset=utf-8
    
    HELLO GOPHER!
     */
    
    
  • 相关阅读:
    react.js
    shell if,case,for,while语法
    shell判断文件类型和权限
    shell编程之sed语法
    php魔术方法__SET __GET
    git 忽略文件.gitignore
    php设置错误,错误记录
    linux ifconfig显示 command not found
    数据库备份与恢复
    mysql主要技术
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635816.html
Copyright © 2011-2022 走看看