golang基础-服务端、客户端VS服务端、TCP请求数据

前端之家收集整理的这篇文章主要介绍了golang基础-服务端、客户端VS服务端、TCP请求数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

服务端处理流程

服务端:
a. 监听端口
b. 接收客户端的链接
c. 创建goroutine,处理该链接

package main

import (
    "fmt"
    "net"
)

func main() {
    fmt.Println("start server...")
    listen,err := net.Listen("tcp","0.0.0.0:50000")
    if err != nil {
        fmt.Println("listen Failed,err:",err)
        return
    }
    for {
        conn,err := listen.Accept()
        if err != nil {
            fmt.Println("accept 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("read err:",err)
            return
        }

        fmt.Printf(string(buf[0:n]))
    }
}

在go的终端启动service

然后cmd启动命令窗口

然后在启动的命令行窗口输入内容,然后在go的终端会输输出对应的信息,效果图如下:

客户端VS服务端处理流程

客户端:
a. 建立与服务端的链接
b. 进行数据收发
c. 关闭链接

这个例子需要另外的客户端client代码
clien.go

package main

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

func main() {

    conn,err := net.Dial("tcp","localhost:50000")
    if err != nil {
        fmt.Println("Error dialing",err.Error())
        return
    }

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

tcp获取百度数据

package main

import (
    "fmt"
    "io"
    "net"
)

func main() {

    conn,"www.baidu.com:80")
    if err != nil {
        fmt.Println("Error dialing",err.Error())
        return
    }
    defer conn.Close()
    msg := "GET / HTTP/1.1\r\n"
    msg += "Host:www.baidu.com\r\n"
    msg += "Connection:keep-alive\r\n"
    //msg += "User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/56.0.2924.87 Safari/537.36\r\n"
    msg += "\r\n\r\n"

    //io.WriteString(os.Stdout,msg)
    n,err := io.WriteString(conn,msg)
    if err != nil {
        fmt.Println("write string Failed,",err)
        return
    }
    fmt.Println("send to baidu.com bytes:",n)
    buf := make([]byte, 4096)
    for {
        count,err := conn.Read(buf)
        fmt.Println("count:",count,"err:",err)
        if err != nil {
            break
        }
        fmt.Println(string(buf[0:count]))
    }
}

运行结果如下:

PS E:\golang\go_pro\src\safly> go run tcp.go
send to baidu.com bytes: 63
count: 750 err: <nil>
HTTP/1.1 200 OK
Date: Sun,12 Nov 2017 06:05:34 GMT
Content-Type: text/html
Content-Length: 14613
Last-Modified: Tue,07 Nov 2017 02:55:00 GMT
Connection: Keep-Alive
Vary: Accept-Encoding
Set-Cookie: BAIDUID=9D2FCA4F5E1079FFED3E6E45106DB21E:FG=1; expires=Thu,31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BIDUPSID=9D2FCA4F5E1079FFED3E6E45106DB21E; expires=Thu,31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1510466734; expires=Thu,31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Server: BWS/1.1
X-UA-Compatible: IE=Edge,chrome=1
Pragma: no-cache
Cache-control: no-cache
Accept-Ranges: bytes


count: 4096 err: <nil>
<!DOCTYPE html><!--STATUS OK-->
<html>
<head>
        <Meta http-equiv="content-type" content="text/html;charset=utf-8">
        <Meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <link rel="dns-prefetch" href="//s1.bdstatic.com"/>
        <link rel="dns-prefetch" href="//t1.baidu.com"/>
        <link rel="dns-prefetch" href="//t2.baidu.com"/>
        <link rel="dns-prefetch" href="//t3.baidu.com"/>
        <link rel="dns-prefetch" href="//t10.baidu.com"/>
        <link rel="dns-prefetch" href="//t11.baidu.com"/>
        <link rel="dns-prefetch" href="//t12.baidu.com"/>
        <link rel="dns-prefetch" href="//b1.bdstatic.com"/>
        <title>百度一下,你就知道</title>
        <link href="http://s1.bdstatic.com/r/www/cache/static/home/css/index.css" rel="stylesheet" type="text/css" />
        <!--[if lte IE 8]><style index="index" >#content{height:480px\9}#m{top:260px\9}</style><![endif]-->
        <!--[if IE 8]><style index="index" >#u1 a.mnav,#u1 a.mnav:visited{font-family:simsun}</style><![endif]-->
        <script>var hashMatch = document.location.href.match(/#+(.*wd=[^&].+)/);if (hashMatch && hashMatch[0] && hashMatch[1]) {document.location. replace("http://"+location.host+"/s?"+hashMatch[1]);}var ns_c = function(){};</script>
        <script>function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('//www.baidu.com/');}</script>
        <noscript><Meta http-equiv="refresh" content="0; url=/baidu.html?from=noscript"/></noscript>
        <script>window._ASYNC_START=new Date().getTime();</script>
</head>
<body link="#0000cc"><div id="wrapper" style="display:none;"><div id="u"><a href="//www.baidu.com/gaoji/preferences.html" onmousedown="return use r_c({'fm':'set','tab':'setting','login':'0'})">搜索设置</a>|<a id="btop" href="/" onmousedown="return user_c({'fm':'set','tab':'index','login':'0 '})">百度首页</a>|<a id="lb" href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" onclick="return false;" onmousedo wn="return user_c({'fm':'set','tab':'login'})">登录</a><a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2 F" onmousedown="return user_c({'fm':'set','tab':'reg'})" target="_blank" class="reg">注册</a></div><div id="head"><div class="s_nav"><a href="/" class="s_logo" onmousedown="return c({'fm':'tab','tab':'logo'})"><img src="//www.baidu.com/img/baidu_jgylogo3.gif" width="117" height="38" border= "0" alt="到百度首页" title="到百度首页"></a><div class="s_tab" id="s_tab"><a href="http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=" wdfield="wor d" onmousedown="return c({'fm':'tab','tab':'news'})">新闻</a>&#12288;<b>网页</b>&#12288;<a href="http://tieba.baidu.com/f?kw=&fr=wwwt" wdfield="k w" onmousedown="return c({'fm':'tab','tab':'tieba'})">贴吧</a>&#12288;<a href="http://zhidao.baidu.com/q?ct=17&pn=0&tn=ikaslist&rn=10&word=&fr=ww wt" wdfield="word" onmousedown="return c({'fm':'tab','tab':'zhidao'})">知道</a>&#12288;<a href="http://music.baidu.com/search?fr=ps&key=" wdfield ="key" onmousedown="return c({'fm':'tab','tab':'music'})">音乐</a>&#12288;<a href="http://image.baidu.com/i?tn=baiduimage&ps=1&ct=201326592&lm=-1 &cl=2&nc=1&word=" wdfield="word" onmousedown="return c({'fm':'tab','tab':'pic'})">图片</a>&#12288;<a href="http://v.baidu.com/v?ct=301989888&rn=2 0&pn=0&db=0&s=25&word=" wdfield="word" onmousedown="return c({'fm':'tab','tab':'video'})">视频</a>&#12288;<a href="http://map.baidu.com/m?word=& fr=ps01000" wdfield="word" onmousedown="return c({'fm':'tab','tab':'map'})">地图</a>&#12288;<a href="http://wenku.baidu.com/search?word=&lm=0&od= 0" wdfield="word" onmousedown="return c({'fm':'tab','tab':'wenku'})">文库</a>&#12288;<a href="//www.baidu.com/more/" onmousedown="return c({'fm' :'tab','tab':'more'})">更多»</a></div></div><form id="form" name="f" action="/s" class="fm" ><input type="hidden" name="ie" value="utf-8"><input t ype="hidden" name="f" value="8"><input type="hidden" name="rsv_bp" value="1"><span class="bg s_ipt_wr"><input name="wd" id="kw" class="s_ipt" valu e="" maxlength="100"></span><span class="bg s_btn_wr"><input type="submit" id="su" value="百度 count: 4096 err: <nil> 一下" class="bg s_btn" onmousedown="this.className='bg s_btn s_btn_h'" onmouSEOut="this.className='bg s_btn'"></span><span class="tools"><span id= "mHolder"><div id="mCon"><span>输入法</span></div><ul id="mMenu"><li><a href="javascript:;" name="ime_hw">手写</a></li><li><a href="javascript:;" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="javascript:;" name="ime_cl">关闭</a></li></ul></span><span class="shouji"><strong>推荐
&nbsp;:&nbsp;</strong><a href="http://w.x.baidu.com/go/mini/8/10000020" onmousedown="return ns_c({'fm':'behs','tab':'bdbrowser'})">百度浏览器,打
开网页快2秒!</a></span></span></form></div><div id="content"><div id="u1"><a href="http://news.baidu.com" name="tj_trnews" class="mnav">新闻</a>< a href="http://www.hao123.com" name="tj_trhao123" class="mnav">hao123</a><a href="http://map.baidu.com" name="tj_trmap" class="mnav">地图</a><a hr ef="http://v.baidu.com" name="tj_trvideo" class="mnav">视频</a><a href="http://tieba.baidu.com" name="tj_trtieba" class="mnav">贴吧</a><a href="ht tps://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" id="lb" onclick="return false;">登录</a><a href="//www. baidu.com/gaoji/preferences.html" name="tj_settingicon" id="pf">设置</a><a href="//www.baidu.com/more/" name="tj_briicon" id="bri">更多产品</a></d iv><div id="m"><p id="lg"><img src="//www.baidu.com/img/bd_logo.png" width="270" height="129"></p><p id="nv"><a href="http://news.baidu.com">新&nb
sp;闻</a> <b>网&nbsp;页</b> <a href="http://tieba.baidu.com">贴&nbsp;吧</a> <a href="http://zhidao.baidu.com">知&nbsp;道</a> <a href="http://m usic.baidu.com">音&nbsp;乐</a> <a href="http://image.baidu.com">图&nbsp;片</a> <a href="http://v.baidu.com">视&nbsp;频</a> <a href="http://map. baidu.com">地&nbsp;图</a></p><div id="fm"><form id="form1" name="f1" action="/s" class="fm"><span class="bg s_ipt_wr"><input type="text" name="wd" id="kw1" maxlength="100" class="s_ipt"></span><input type="hidden" name="rsv_bp" value="0"><input type=hidden name=ch value=""><input type=hidden name=tn value="baidu"><input type=hidden name=bar value=""><input type="hidden" name="rsv_spt" value="3"><input type="hidden" name="ie" value="ut f-8"><span class="bg s_btn_wr"><input type="submit" value="百度一下" id="su1" class="bg s_btn" onmousedown="this.className='bg s_btn s_btn_h'" onm ouSEOut="this.className='bg s_btn'"></span></form><span class="tools"><span id="mHolder1"><div id="mCon1"><span>输入法</span></div></span></span>< ul id="mMenu1"><div class="mMenu1-tip-arrow"><em></em><ins></ins></div><li><a href="javascript:;" name="ime_hw">手写</a></li><li><a href="javascri pt:;" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="javascript:;" name="ime_cl">关闭</a></li></ul></div><p id="lk"><a href="http://b aike.baidu.com">百科</a> <a href="http://wenku.baidu.com">文库</a> <a href="http://www.hao123.com">hao123</a><span>&nbsp;|&nbsp;<a href="//www.b aidu.com/more/">更多&gt;&gt;</script>
</body></html>
count: 0 err: EOF
PS E:\golang\go_pro\src\safly>
原文链接:https://www.f2er.com/go/187713.html

猜你在找的Go相关文章